import {App} from "./App";
import debug from "debug";
import {WebsocketApp} from "./WebsocketApp";
import {Database} from "./database/Database";
import {iTender} from "./iTender";
import {iTenderStatus} from "./iTenderStatus";
import {Utils} from "./Utils";
import {Settings} from "./Settings";

const log = debug("itender:server");

const app = new App();
const wsApp = new WebsocketApp();


(async () => {
    try {
        log("Starting...");
        await Database.connect();
        //await test();
        await app.listen();
        await wsApp.listen();
        Settings.loadSettings();

        iTender.setStatus(iTenderStatus.STARTING);
        await Utils.sleep(2000);

        if (!Settings.setupDone) {
            iTender.setStatus(iTenderStatus.SETUP);
            log("iTender is not set up yet!");
        }


        function checkStart() {
            setTimeout(async () => {
                if (!Settings.setupDone) {
                    checkStart();
                    return;
                }
                Settings.saveSettings();


                await init();
                setInterval(refresh, 1000 * 60);
                iTender.setStatus(iTenderStatus.READY);
            }, 1000);
        }

        checkStart();

    } catch (e) {
        console.error("---- ERROR ----");
        console.error(e);
        process.exit(-1);
    }
})();

function init(): Promise<void> {
    log("Initializing...");
    return new Promise(async resolve => {
        iTender.setStatus(iTenderStatus.STARTING);

        setTimeout( async () => {
            // Network
            await iTender.checkNetwork();
            if (iTender.internetConnection && iTender.status == iTenderStatus.READY) {
                await iTender.refreshFromServer();
            }
        }, 1000 * 20 ) ;


        // Containers
        //await iTender.refreshContainers();
        await iTender.measureContainers();
        // Drinks
        await iTender.refreshDrinks();
        // Start auto checkup for stuck jobs
        await iTender.autoCheckup();

        resolve();
    });
}

function refresh(): Promise<void> {
    return new Promise(async resolve => {
        log("Refreshing...")
        // Network
        await iTender.checkNetwork();

        // Below are refreshments of containers / drinks

        // If there is a current job, DO NOT REFRESH!
        if (iTender.currentJob)
            return;

        //await iTender.refreshContainers(); Not needed because there is no change in containers?
        await iTender.measureContainers();
        //await iTender.refreshDrinks(); Not needed because there is no change in drinks?
    });
}