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

function getData(file, isMap) {
  if (!fs.existsSync(file)) {
    return null;
  }
  let data;
  data = fs.readFileSync(file);
  try {
    data = JSON.parse(data.toString());
  }
  catch (e) {
    data = (isMap ? {} : []);
  }
  return data;
}

function setData(file, data, callback) {
  if (typeof (data) != 'string') {
    try {
      data = JSON.stringify(data)
    }
    catch (error) {
      callback?.(error);
    }
  }
  const directoryPath = path.dirname(file);
  if(!fs.existsSync(directoryPath)) {
    fs.mkdirSync(directoryPath, { recursive: true });
  }

  try {
    fs.writeFileSync(file, data);
    callback?.();
  }
  catch (error) {
    callback?.(error);
  }
}

export { getData, setData };
export default { getData, setData };
