'use strict';
   
const serverRuleUtils = require('../ruleengine/ServerRuleUtils');
const scheduleUtils = require('../ruleengine/ScheduleUtils');

const express = require('express');
const http    = require('http');
const socket  = require('../socket/SocketServer');

let startProcessingFunc;
   
let systemActionPollTime = config.get("systemActionPollTime");
if (!systemActionPollTime) {
    systemActionPollTime = 20000;
}

function start() {
    let port = config.get('systemActionPort') || 3030;
    
    const isStartScheduleDocument =  (process.argv.length > 2
        && process.argv[2].trim().toLowerCase() === 'scheduledocuments' );

    startProcessingFunc = serverRuleUtils.processUnactionedSystemActions;

    if (isStartScheduleDocument){
        startProcessingFunc = scheduleUtils.processScheduleDocuments;
        port = config.get('schedulePort') || 3031;
    }

    const app = express();
    const server = http.createServer(app).listen(port);
    socket.listen(server, app);
            
    DataService.initialise()
        .then(function successFunc() {

            const startMsg = isStartScheduleDocument ? "Schedule Document" : "System Action" ;
            utilBanner.printCompletionBanner(startMsg + " Processor started at port " + port);

            startPollProcess();

        }, function errorFunc(err) {
            logger.error("Error initialising dataService: " + err);
            exit(1);
        });
}

function startPollProcess() {
    startProcessingFunc().then(() => pollProcess()).catch((error) => {
        logger.error("Error: " + error);
        pollProcess();
    });
}

function pollProcess() {
    setTimeout(startPollProcess, systemActionPollTime);   
};

function exit(exitCode, exitWait) {
    if (!exitWait) {
        exitWait = 60000;
    }
    logger.warn("Exiting process in " + exitWait + "ms.");

    setTimeout(function() {
        logger.warn("Exiting...");
        process.exit(exitCode);
    }, exitWait);
}


////////////////////////////////////
// public api
var SystemActionProcessor = {

    start: start

};

module.exports = SystemActionProcessor;

