const updater = require('electron-simple-updater');
const log = require('electron-log');
const moment = require('moment');

const contentLoader = require('../../modules/content-loader');
const downloader = require('./update-downloader');
const getParams = require('../../modules/get-params');

let updateTimeout;
let isInitedSimpleUpdater = false;

const createTaskForInitUpdate = async (datetimeSec) => {
    try {
        const updateMs = moment(datetimeSec * 1000).add(-1, 'hours').format('x') - moment().format('x');
        const updateMsAfter = moment(datetimeSec * 1000).format('x') - moment().format('x');
        const setUpdateTimeout = (delay) => {
            log.warn('helper:app-updater:createTaskForInitUpdate need update app after '+ delay + ' sec.');

            clearTimeout(updateTimeout);

            updateTimeout = setTimeout(async () => {
                if ( !isInitedSimpleUpdater ) {
                    isInitedSimpleUpdater = true;

                    const urlForUpdate = await getUpdateUrl();

                    updater.init({
                        url: urlForUpdate,
                        checkUpdateOnStart: false,
                        autoDownload: false,
                        logger: false
                    });

                    updater.on('checking-for-update', _eventCheckUpdates);
                    updater.on('update-available', _eventUpdateAvailable);
                    updater.on('update-not-available', _eventUpdateNotAvailable);
                    updater.on('update-downloading', _eventUpdateDownloading);
                    updater.on('update-downloaded', _eventUpdateDownloaded);
                    updater.on('error', _eventUpdateError);
                }

                updater.checkForUpdates();
            }, delay);
        };

        log.warn('upd app before?',updateMs,(-updateMs < (1000 * 60 * 60)));

        if ( updateMs < 0 && (-updateMs < (1000 * 60 * 60)) ) {
            setUpdateTimeout(0);
        } else if ( updateMsAfter >= 0 ) {
            setUpdateTimeout(updateMsAfter);
        } else {
            log.error('helper:app-updater:createTaskForInitUpdate error get seconds to update');
        }
    } catch (err) {
        log.error('helper:app-updater createTaskForInitUpdate() broken', err);
    }
};

const getUpdateUrl = async () => {
    try {
        const {appConfig} = await getParams('appConfig');
        let ip = appConfig.remote_href;

        if ( ip.lastIndexOf(':') > 7 ) {
            ip = ip.substr(0, ip.lastIndexOf(':'));
        }

        const urlForUpdate = ip +'/electron-builds/updates.json';

        log.warn('update app url:', urlForUpdate);

        return urlForUpdate;
    } catch (e) {
        log.error('helper:app-updater getUpdateUrl() broken', e);
    }
};

const _eventCheckUpdates = () => {
    try {
        log.info('Checking for updates...');
    } catch (e) {
        log.error('', e);
    }
};

const _eventUpdateAvailable = (meta) => {
    try {
        contentLoader.disable();

        updater.downloadUpdate();

        return false;

        if (process.platform === 'linux') {
            if (!downloader.isDownloading()) {
                downloader.downloadUpdate(meta);
            }
        } else {
            updater.downloadUpdate();
        }
    } catch (e) {
        log.error('', e);
    }
};

const _eventUpdateNotAvailable = () => {
    try {
        log.info('Update is not available');
    } catch (e) {
        log.error('', e);
    }
};

const _eventUpdateDownloading = (meta) => {
    try {
        log.info('Downloading update version:', meta.version);
    } catch (e) {
        log.error('', e);
    }
};

const _eventUpdateDownloaded = (meta) => {
    try {
        log.warn('Update downloaded, installing.');

        if (process.platform === 'linux') {
            updater.quitAndInstall(meta);
        } else {
            updater.quitAndInstall();
        }
    } catch (e) {
        log.error('', e);
    }
};

const _eventUpdateError = (meta) => {
    try {
        log.error(meta);
        contentLoader.enable();
    } catch (e) {
        log.error('', e);
    }
};

module.exports = {
    createTaskForInitUpdate: createTaskForInitUpdate
};
