const Constants = require('../../constants');
const fs = require('fs');
const helpers = require('../../helpers');
const path = require('path');

const addListeners = ipcMain => {
  ipcMain.on(Constants.IPC_Get_State, event => {
    helpers.mkDirByPathSync(helpers.getDataDirectory());
    const configFile = path.join(helpers.getDataDirectory(), 'settings.json');
    if (fs.existsSync(configFile)) {
      event.sender.send(Constants.IPC_Get_State_Reply, {
        data: JSON.parse(fs.readFileSync(configFile, 'utf8')),
      });
    } else {
      event.sender.send(Constants.IPC_Get_State_Reply, {
        data: null,
      });
    }
  });

  ipcMain.on(Constants.IPC_Save_State, (event, data) => {
    helpers.mkDirByPathSync(helpers.getDataDirectory());
    const configFile = path.join(helpers.getDataDirectory(), 'settings.json');
    fs.writeFileSync(configFile, JSON.stringify(data.State), 'utf8');
  });
};

module.exports = {
  addListeners
};