import fs from 'fs';
import path from 'path';

export const getData = (file) => {
  let data = null;

  if (fs.existsSync(file)) {
    const arrayBuffer = fs.readFileSync(file);

    try {
      data = JSON.parse(arrayBuffer.toString());
    }
    catch (e) {}
  }

  return Promise.resolve(data);
}

export const setData = (file, data, indent = 2) => {
  return new Promise((resolve, reject) => {

    if (typeof (data) != 'string') {
      try {
        data = JSON.stringify(data, null, indent);
      }
      catch (error) {
        reject(error);
      }
    }

    const directoryPath = path.dirname(file);
    if(!fs.existsSync(directoryPath)) {
      fs.mkdirSync(directoryPath, { recursive: true });
    }

    try {
      fs.writeFileSync(file, data);
      resolve();
    }
    catch (error) {
      reject(error);
    }
  });
}