const {app} = require('electron');
const remote = require('electron').remote;
const url = require('url');
const path = require('path');
const log = require('electron-log');
const moment = require('moment');
const fs = require('fs');
const fetch = require('node-fetch');
const _ = require('lodash');

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

module.exports.update = function (id, startTimeMs) {
    try {
        const appUserData = (app ? app.getPath('userData') : remote.app.getPath('userData'));
        const dirPath = path.join(appUserData, 'repeats');
        const fileName = moment(startTimeMs).format('YYYY-MM-DD_HH') +'.json';
        const filePath = path.join(dirPath, fileName);

        if ( !fs.existsSync(dirPath) ) {
            fs.mkdirSync(dirPath);
        }

        if ( !fs.existsSync(filePath) ) {
            fs.writeFileSync(filePath, JSON.stringify([]));
        }

        const json = JSON.parse(fs.readFileSync(filePath));//log.error(json);
        json[json.length] = {
            content: id,
            time: moment(startTimeMs).toDate()
        };

        fs.writeFileSync(filePath, JSON.stringify(json));
    } catch (err) {
        log.error('mod:repeats:update():', err);
    }
};

module.exports.sendStats = async () => {
    // %server%/devices/stat/%device_id%
    try {
        const {appConfig} = await getParams('appConfig');
        const href = new URL(appConfig.device._id, new URL('/devices/stat/', appConfig.remote_href).href);

        const today = moment().format('YYYY-MM-DD');
        const dir = path.join(app.getPath('userData'), 'repeats');

        if ( !fs.existsSync(dir) ) {
            return log.error('mod:repeats:sendStats(): repeats dir not exists');
        }

        fs.readdir(dir, function(err, filenames) {
            if (err) {
                log.error('mod:repeats:sendStats(): fs.readdir(%userData%/repeats)');
                return new Error('mod:repeats:sendStats(): fs.readdir(%userData%/repeats)');
            }

            filenames.forEach(function(filename, fileIndex) {
                const filenameArr = path.parse(filename);

                if ( filenameArr.ext !== '.json' || !moment(filenameArr.name,'YYYY-MM-DD_HH').isValid() || filenameArr.name === moment().format('YYYY-MM-DD_HH') ) {
                    return false;
                }
                const body = fs.readFileSync(path.join(dir, filenameArr.base), 'utf-8');
                // log.error(body)
                promiseTimeout(fetch(href, {
                    cache: 'no-cache',
                    method: 'post',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: body
                }))
                // .then((re) => re.json())
                    .then((re) => {
                        log.error('mod:repeats:sendStats():', filenameArr.base, 'sended!', re);
                        fs.unlinkSync(path.join(dir, filenameArr.base));
                    })
                    .catch((err) => {
                        log.error('mod:repeats:sendStats(): fetch error', err);
                    });
            });
        });
    } catch (err) {
        log.error('mod:repeats:sendStats():', err);
    }
};
