const {app} = require('electron');
const log = require('electron-log');
const fetch = require('node-fetch');
const fs = require("fs")

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

module.exports = () => {
    try {
        return new Promise(async (resolve, reject) => {
            const {
                appConfig, ipAddress, macAddress, serverPort
            } = await getParams('appConfig', 'ipAddress', 'macAddress', 'serverPort');

            const appVersion = app.getVersion();
            //let remoteDataSrc = `${appConfig.remote_href}/devices/whoami?device=`;
            let remoteDataSrc = `${appConfig.remote_href}/devices/mybroadcast?device=`;
            remoteDataSrc += `${appConfig.device._id}`;
            remoteDataSrc += `&ip=${ipAddress}:${serverPort}`;
            remoteDataSrc += `&mac=${macAddress}`;
            remoteDataSrc += `&appversion=${appVersion}`;

            log.info('getRemoteJson() from:', remoteDataSrc);

            promiseTimeout(fetch(remoteDataSrc, {
                cache: 'no-cache'
            }))
                .then((re) => re.json())
                .then(async (re) => {
                    if ( typeof re === 'object' && re['last_update'] ) {
                        const result = await dataController.updateInfoAndGetWithBroadcasts(re);

                        resolve(result);
                    } else {
                        log.error('very bad json!');
                        reject(new Error('very bad json!'));
                    }
                })
                .catch(er => {
                    log.error('getRemoteJson() fetch error', er);
                    reject(new Error('getRemoteJson() fetch error'));
                });
        });
    } catch (e) {
        log.error('mod:get-remote-json broken', e);
    }
};
