let { app } = require('electron');
const log = require('electron-log');// error // warn // info // verbose // debug // silly

const { checkDataIsConfig } = require('./utils.js');

const isMainProcess = !!(app);

const saveToCache = (config = null) => {
    try {
        if (!checkDataIsConfig(config)) {
            log.warn('[neuroAd] send machine config for cache is bad');

            return;
        }

        if (isMainProcess) {
            if (!global?.gApp) global.gApp = {};
            if (!global?.gApp?.neuroAd) global.gApp.neuroAd = {};

            global.gApp.neuroAd.configMachine = config;
        } else {
            if (!window?.app) window.app = {};
            if (!window?.app?.neuroAd) window.app.neuroAd = {};

            window.app.neuroAd.configMachine = config;
        }
    } catch (e) {
        log.error('[neuroAd] error update cache machine config\n', e);
    }
};

const getFromCache = () => {
    if (isMainProcess) {
        return !global?.gApp?.neuroAd?.configMachine || null;
    } else {
        return window?.app?.neuroAd?.configMachine || null;
    }
};

module.exports = {
    saveToCache,
    getFromCache
};
