const { ipcMain } = require('electron');
const log = require('electron-log');
const moment = require('moment');

const getJsonData = require('../modules/jsondata/get-json-data');
const dataController = require('../modules/jsondata/data-controller');
const contentLoader = require('../modules/content-loader');
const getAppWindow = require('../modules/getAppWindow.js');
const getParams = require('../modules/get-params');
const extractButtons = require('../modules/buttons/extract-buttons');
const buttonsModule = require("../modules/buttons/buttons");
const { forMain } = require('../configs-constants/eventNames.js');

let lastUpdatesData = {
    _ads: null,
    _info: null,
    _button: null
};

{
    ipcMain.on(forMain.pageReady, () => {
        log.info(forMain.pageReady);

        lastUpdatesData = {
            _ads: null,
            _info: null,
            _button: null
        };
    });
}

const getData = () => {
    try {
        if ( contentLoader.isDownloading() ) {
            return;
        }

        getJsonData()
            .then(async (re) => {
                const neuroAdWindow = getAppWindow('main');
                const {appConfig, appParams} = await getParams('appConfig', 'appParams');
                const g_volume = (re.g_volume && re.g_volume > 0 ? re.g_volume : 0);

                neuroAdWindow.webContents.send('msg', { type: 'g_volume', msg: g_volume });

                const isNeedToUpdateAds = checkForNeedToUpdate(re.last_update._ads, lastUpdatesData._ads);
                const isNeedToUpdateInfo = checkForNeedToUpdate(re.last_update._info, lastUpdatesData._info);
                const isNeedToUpdateButton = checkForNeedToUpdate(re.last_update._button, lastUpdatesData._button);

                log.info(`is need to update ads:${isNeedToUpdateAds}, info:${isNeedToUpdateInfo}, buttons:${isNeedToUpdateButton}`);

                if ( !isNeedToUpdateAds && !isNeedToUpdateInfo && !isNeedToUpdateButton ) {
                    return false;
                }

                // log.info('update data by:', re);

                const main_ip = clearIp(re.main_ip);
                const ip = clearIp(re.ip);
                const forDownloadArr = [];

                if ( isNeedToUpdateAds ) {
                    forDownloadArr.push(re.data['_ads']);
                }

                if ( isNeedToUpdateInfo ) {
                    forDownloadArr.push(re.data['_info']);
                }

                if ( isNeedToUpdateButton ) {
                    forDownloadArr.push(re.data['_button']);
                    neuroAdWindow.webContents.send('blockPlayButtons', true);
                }

                log.info('ip:', ip, 'main_ip: ', main_ip, 'myip: ', appParams.get('ipAddress'));

                const hrefMain = await getMainMachineHref(main_ip);
                const hrefRemote = appConfig.remote_href;

                if ( forDownloadArr.length > 0 ) {
                    download(forDownloadArr, hrefMain, hrefRemote)
                        .then(() => {
                            neuroAdWindow.webContents.send('msg', {type: 'newData', msg: {data: re.data}});

                            dataController.updateInfoData(re);
                            lastUpdatesData = re.last_update;

                            if ( isNeedToUpdateButton ) {
                                extractButtons(re.data);

                                buttonsModule.isNeedUpdateContent()
                                    .then(() => {
                                        neuroAdWindow.webContents.send('unBlockPlayButtons', true);
                                    })
                                    .catch(() => {

                                    });
                            }
                        })
                        .catch((e) => {
                            log.error(e);
                        });
                } else {
                    neuroAdWindow.webContents.send('unBlockPlayButtons', true);
                }
            })
            .catch(err => {
                log.error(err);
            });
    } catch (err) {
        log.error('helper:checkUpdateDataInfoAndBroadcasts getData() broken', err);
    }
};

const download = (forDownloadArr, hrefMain, hrefRemote) => {
    try {
        return new Promise((resolve, reject) => {
            /* downloading files */
            const downloading = function (data) {
                contentLoader.download(data, hrefMain, hrefRemote)
                    .then(() => {
                        forDownloadArr = forDownloadArr.slice(1);

                        if (forDownloadArr.length > 0) {
                            downloading(forDownloadArr[0]);
                        } else {
                            resolve();
                        }
                    })
                    .catch((err) => {
                        log.error('download content failed', err);
                        reject();
                    });
            };

            downloading(forDownloadArr[0]);
        });
    } catch (err) {
        log.error('helper:checkUpdateDataInfoAndBroadcasts download() broken', err);
    }
};

const clearIp = (ip) => {
    try {
        if ( ip && ip.indexOf('://') > 0 ) {
            ip = ip.substr(ip.indexOf('://') + 3);
        }

        if ( ip && ip.indexOf(':') > 0 ) {
            ip = ip.substr(0, ip.indexOf(':'));
        }

        return ip;
    } catch (e) {
        log.error('helper:checkUpdateDataInfoAndBroadcasts clearIp() broken', e);
    }
};

const getMainMachineHref = async (main_ip) => {
    try {
        const {appParams} = await getParams('appParams');
        let result = null;

        if ( main_ip && main_ip !== appParams.get('ipAddress') ) {
            result = 'http://'+ main_ip +':'+ appParams.get('serverPort');
        }

        return result;
    } catch (e) {
        log.error('helper:checkUpdateDataInfoAndBroadcasts getMainMachineHref() broken', e);
    }
};

const checkForNeedToUpdate = (curDate, newDate) => {
    try {
        let result = true;

        if ( !curDate && !newDate ) {
            result = false;
        } else if ( curDate && moment(curDate).isValid() && newDate && moment(newDate).isValid() ) {
            if ( curDate === newDate ) {
                result = false;
            }
        }

        return result;
    } catch (e) {
        log.error('', e);
    }
};

module.exports = getData;
