const os = require('os');
const fetch = require('node-fetch');
const diskspace = require('diskspace');
const log = require('electron-log');// error // warn // info // verbose // debug // silly
const path = require('path');
const url = require('url');

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

module.exports = async () => {
    try {
        const {appConfig, appUserData} = await getParams('appConfig', 'appUserData');
        const hard = path.parse(appUserData).root;
        const href = new URL('devices/monitor/'+ appConfig.device._id, appConfig.remote_href).href;

        if ( !hard || !href ) {
            log.error(`don't get main hard disk: '${hard}' or href: '${href}' for send statistics`);
            return false;
        }

        diskspace.check(hard, function (err, result) {
            if ( err ) {
                log.error(err);
                restart();

                return false;
            }

            promiseTimeout(fetch(href, {
                method: 'post',
                cache: 'no-cache',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    hard: result,
                    loadavg: os.loadavg(),
                    memory: {
                        free: os.freemem(),
                        total: os.totalmem()
                    }
                })
            }))
                .then(re => {
                    log.warn('mod:send-os-monitoring', 'sended!');
                    restart();
                })
                .catch(err => {
                    log.error(err);
                    restart();
                });
        });

        const restart = function () {
            setTimeout(() => {
                getAndSend();
            }, 1000 * 60 * 5);
        };
    } catch (err) {
        log.error('mod:send-os-monitoring', err);
    }
};
