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

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

const checkAll = (toDownloadArr, mainMachineUrl) => {
    try {
        return new Promise((resolve, reject) => {
            promiseTimeout(fetch(url.resolve(mainMachineUrl, '/check-content/'), {
                cache: 'no-cache',
                method: "POST",
                body: JSON.stringify(toDownloadArr),
                headers: {
                    "Content-Type": "application/json"
                }
            }))
                .then(re => re.text())
                .then(re => {
                    if ( re === 'ok' ) {
                        log.info(`mod:check-items-on-local-machine`, 'all files checked successfully');
                    } else {
                        log.info(`mod:check-items-on-local-machine`, 'one or more files not found');
                    }

                    resolve(re);
                })
                .catch((err) => {
                    log.error(`mod:check-items-on-local-machine fetch broken`, err);
                    reject();
                });
        });
    } catch (e) {
        log.error('mod:check-item-on-servers check() f-n broken', e);
    }
};

module.exports = {
    checkAll: checkAll
};
