// let path = require("path");
// const packageJson = require("../../package");
// const appName = (packageJson.name !== 'undefined') ? packageJson.name : 'metro';
// const TConfig = require("../../modules/config/js/config");
// let appPath = process.cwd();
const { app, ipcMain } = require('electron');
const path = require("path");

let conf = {};
const appParams = new Map();

const autoInit = (mainWindow, requestInterval) => {
    let isInited = false;

    ipcMain.on("neuroAd_pageInitialized", (event, args) => {
        if (!isInited) {
            isInited = true;
            init(mainWindow, requestInterval);
        } else {
            console.log('ELSEeeeeeeeeeeeeeeeeeeeeee', mainWindow.webContents.send)
            mainWindow.webContents.send('msg',{ type: 'device_orientation', msg: conf.device.device_orientation });
            mainWindow.webContents.send('msg',{ type: 'appUserDataPath', msg: path.join(app.getPath('userData'), 'neuroad') });
            mainWindow.webContents.send('msg',{ type: 'savedJsonDir', msg: appParams.get('savedData') });
            mainWindow.webContents.send('msg',{ type: 'createWebSocket', msg: {href: conf.remote_href, conf: conf} });
            mainWindow.webContents.send('msg',{ type: 'init', msg: true });
        }
    });
};

const init = (win, requestInterval) => {
    const electron = require('electron');
    const isDev = require('electron-is-dev');
    const moment = require('moment');
    const getIp = require('ip');

    const log = require('electron-log');

    const getLocalConfig = require('./modules/configMachine/getMachineConfig.js');
    // const scheduler = require('./modules/scheduler');
    const sendOsMonitoring = require('./modules/send-os-monitoring');
    const reboot = require('./modules/reboot');
    const repeats = require('./modules/repeats');
// const contentCleaner = require('./modules/content-cleaner');
    const getMacAddress = require('./modules/getMacAddress');
    const checkUpdateDataInfoAndBroadcasts = require('./helpers/check-update-info-data-and-broadcasts');
    // const appUpdater = require('./helpers/app-updater');
    const devToolsAutoClose = require('./helpers/dev-tools-auto-close');
    const serverWorker = require('./helpers/server-worker');
    const renameAppFile = require('./helpers/rename-app-file');

    const interval = requestInterval ? requestInterval : 3000;

    moment.locale('en');

    let onlineStatus = false;
    let lastUnixMsTime = false;
    let firstSwitchToOnline = false;
    const initEvery = Object.freeze({
        'tacts_300': {
            index: 0,
            value: 300
        },
        'tacts_1800': {
            index: 0,
            value: 1800
        },
    });

    appParams.set('savedData', path.join(app.getPath('userData'), 'neuroad'));
    appParams.set('ipAddress', getIp.address('public', 'ipv4'));
    appParams.set('macAddress', getMacAddress());
    appParams.set('serverPort', 3000);

    const getConf = function (interval) {
        getLocalConfig()
            .then((re) => {
                conf = re;

                log.info('my ip: '+ appParams.get('ipAddress'));

                win.webContents.send('msg',{ type: 'device_orientation', msg: conf.device.device_orientation });
                win.webContents.send('msg',{ type: 'appUserDataPath', msg: path.join(app.getPath('userData'), 'neuroad') });
                win.webContents.send('msg',{ type: 'savedJsonDir', msg: appParams.get('savedData') });
                win.webContents.send('msg',{ type: 'createWebSocket', msg: {href: conf.remote_href, conf: conf} });
                win.webContents.send('msg',{ type: 'init', msg: true });

                // serverWorker();

                setTimeout(() => secondLoop(interval), 3000);

                // require('./modules/clear-app-dir')();
            })
            .catch(err => {
                log.error(err);

                setTimeout(getConf, 5000);
            });
    };

    getConf(interval);

    const nowOnline = function () {
        try {
            appParams.set('ipAddress', getIp.address('public', 'ipv4'));

            if ( !firstSwitchToOnline ) {
                firstSwitchToOnline = true;

                // scheduler();
                // repeats.sendStats();

                if ( process.platform === 'linux' ) {
                    // sendOsMonitoring();
                }
            }
        } catch (err) {
            log.error('index:nowOnline()', err);
        }
    };

    const secondLoop = (interval) => {
        setInterval(() => {
            try {
                for ( let key in initEvery ) {
                    initEvery[key].index++;
                }

                if ( !win || !conf || !conf.remote_href ) {// app not init
                    return false;
                }

                const nowMoment = moment();
                const now = nowMoment.unix();
                const nowMs = nowMoment.format('x');
                const difference = nowMs - lastUnixMsTime;

                if ( lastUnixMsTime && (difference > 2000 || difference < 0) ) {
                    if ( process.platform === 'linux' ) {
                        log.warn('time updated, init restart app');
                        reboot.roskomnadzor();
                    }
                }

                lastUnixMsTime = nowMs;

                checkUpdateDataInfoAndBroadcasts();

                for ( let key in initEvery ) {
                    if ( key === 'tacts_300' && initEvery[key].index === initEvery[key].value ) {
                        if ( onlineStatus ) {
                            // scheduler();
                        }

                        initEvery[key].index = 0;
                    } else if ( key === 'tacts_1800' && initEvery[key].index === initEvery[key].value ) {
                        if ( onlineStatus ) {
                            repeats.sendStats();
                        }

                        initEvery[key].index = 0;
                    }
                }
            } catch (err) {
                log.error('index:setInterval()', err);
            }
        }, interval);
    };

    const msgListeners = function () {
        try {
            ipcMain.on('msg', (event, arg) => {
                log.info(arg);
            });

            ipcMain.on('openDevTools', (event, arg) => {
                //win.webContents.openDevTools();
            });

            ipcMain.on('get-param', (paramName) => {
                switch ( paramName ) {
                    case('appConfig'):
                        ipcMain.emit('send-param', conf);
                        break;
                    case('appUserData'):
                        ipcMain.emit('send-param', path.join(app.getPath('userData'),'neuroad'));
                        break;
                    case('savedDataPath'):
                        ipcMain.emit('send-param', appParams.get('savedData'));
                        break;
                    case('uploadsPath'):
                        ipcMain.emit('send-param', path.join(app.getPath('userData'), 'neuroad' , 'uploads'));
                        break;
                    case('ipAddress'):
                        ipcMain.emit('send-param', appParams.get('ipAddress'));
                        break;
                    case('macAddress'):
                        ipcMain.emit('send-param', appParams.get('macAddress'));
                        break;
                    case('serverPort'):
                        ipcMain.emit('send-param', appParams.get('serverPort'));
                        break;
                    case('appParams'):
                        ipcMain.emit('send-param', appParams);
                        break;
                }
            });

            ipcMain.on('online-status', (event, arg) => {
                onlineStatus = arg;

                if ( onlineStatus ) {
                    nowOnline();
                }
            });
        } catch (err) {
            log.error('index:msgListeners()', err);
        }
    };

    msgListeners();
};

module.exports = {
    autoInit: autoInit
};
