const { MD5 } = require('./md5.js');
const { networkInterfaces } = require('os');

class ErrorToServiceHandler {
    constructor() {
        this.previousValues = {};

        this.project_id = undefined;

        const nets = networkInterfaces();
        this.ipAddresses = {};

        for (const name of Object.keys(nets)) {
            for (const net of nets[name]) {
                // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
                if (net.family === 'IPv4' && !net.internal) {
                    if (!this.ipAddresses[name]) {
                        this.ipAddresses[name] = [];
                    }
                    this.ipAddresses[name].push(net.address);
                }
            }
        }
    }

    setProjectId(project_id) {
        this.project_id = project_id;
    }

    processMessage(message, seconds) {
        if (Array.isArray(message)) message = message.join(', ');

        let key = MD5(message);
        let ts = Date.now();

        //keep in memory - default value is 1h
        if (seconds === undefined) seconds = 60 * 60;

        if (!this.previousValues.hasOwnProperty(key)) {
            this.previousValues[key] = { ts: ts, duration: seconds };
        }

        let diff = (ts - this.previousValues[key].ts);
        if (diff < this.previousValues[key].duration * 1000) return false;

        this.previousValues[key].ts = ts;

        return message;
    }

    sendMessageToService(message, seconds, message_type) {

        // if error occures too early FLOW.GLOBALS.settings.project_id is still undefined
        if (this.project_id === undefined) {
            console.log("ErrorToServiceHandler.js: no project_id");
            return;
        }

        let f = this.processMessage(message, seconds);
        if (f === false) return;

        if (message_type === undefined) message_type = "error_message";

        let toService = {
            id: this.project_id,
            ipAddresses: this.ipAddresses
        };

        //js_error || error_message
        toService[message_type] = message;

        console.log("ErrorToServiceHandler------------------------>send to service", toService);

        RESTBuilder.make(function(builder) {
            builder.method('POST');
            builder.post(toService);
            builder.url('http://192.168.252.2:8004/sentmessage');

            builder.callback(function(err, response, output) {
                console.log("process.on error send", err, response, output, toService);
            });
        });

    }
}

const errorHandler = new ErrorToServiceHandler();


module.exports = errorHandler;
//module.exports = ErrorToServiceHandler;
