const url = require('url');
const log = require('electron-log');
const fetch = require('node-fetch');

const promiseTimeout = require('../timeout-for-promise.js');

const checkItemOnServers = (itemPath, mainMachineUrl, remoteServerUrl) => {
    try {
        return new Promise((resolve, reject) => {
            const promises = [];

            promises[promises.length] = check(url.resolve(remoteServerUrl, itemPath));

            if ( mainMachineUrl ) {
                promises[promises.length] = check(url.resolve(mainMachineUrl, itemPath));
            }

            Promise.all(promises)
                .then((re) => {
                    resolve({
                        remoteServerHref: re[0],
                        mainMachineHref: re[1]
                    });
                })
                .catch((err) => {
                    log.error(err);
                    reject();
                });
        });
    } catch (e) {
        log.error('mod:check-item-on-servers broken', e);
    }
};

const check = (serverUrl) => {
    try {
        return new Promise((resolve, reject) => {
            promiseTimeout(fetch(serverUrl, {
                cache: 'no-cache'
            }))
                .then(re => {
                    if ( re.status === 200 ) {
                        resolve(serverUrl);
                    } else {
                        log.error(`File: ${serverUrl} not found!`);
                        reject();
                    }
                })
                .catch((err) => {
                    log.error(err);
                    reject();
                });
        });
    } catch (e) {
        log.error('mod:check-item-on-servers check() f-n broken', e);
    }
};

module.exports = checkItemOnServers;
