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

const { saveToCache, getFromCache } = require('./cacheMachineConfig.js');
const { simpleCheckExtension, checkDataIsConfig } = require('./utils.js');

const isMainProcess = !!(app);

if (!isMainProcess) {
    app = require('@electron/remote').app;
}

const searchInDirectory= (directoryPath) => {
    try {
        if (!directoryPath || !fs.existsSync(directoryPath) || !fs.statSync(directoryPath).isDirectory()) {
            return null;
        }

        const filenames = fs.readdirSync(directoryPath).filter((fileName) => simpleCheckExtension(fileName));

        if (filenames.length < 1) {
            return null;
        }

        for (let index = 0; index < filenames.length; index += 1) {
            const filePath = path.join(directoryPath, filenames[index]);
            const content = (fs.statSync(filePath).isFile() ? fs.readFileSync(filePath, 'utf8') : null);
            const parseResult = (content && typeof content === 'string' ? JSON.parse(content) : null);

            if (parseResult && checkDataIsConfig(parseResult)) {
                return parseResult;
            }
        }

        return null;
    } catch (e) {
        log.error('[neuroAd] getLocalConfig() -> searchInDirectory() has broken');

        return null;
    }
};

const getMachineConfig = (configPath) => {
    try {
        let config = null;// getFromCache();

        /*if (config) {
            return config;
        }*/

        const directoriesForSearch = [configPath, process.cwd(), app.getPath('home')];

        for (let index = 0; index < directoriesForSearch.length; index += 1) {
            const directoryPath = directoriesForSearch[index];

            config = searchInDirectory(directoryPath);

            if (config) {
                break;
            }
        }

        if (config.remote_href.indexOf('://') < 0) {
            config.remote_href = 'http://'+ config.remote_href;
        }

        return config;
    } catch (e) {
        log.error('[neuroAd] getLocalConfig() -> getMachineConfig() has broken');

        return null;
    }
};

module.exports = getMachineConfig;
