import {WebSocketPayload} from "../../WebSocketPayload";
import debug from "debug";
import {WebSocketHandler} from "../../WebSocketHandler";
import {iTender} from "../../iTender";
import {iTenderStatus} from "../../iTenderStatus";
import {WebSocketEvent} from "../../WebSocketEvent";
import Container from "../../database/Container";
import {SensorType} from "../../SensorType";

const express = require('express');
const router = express.Router();


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

router.ws('/', async (ws, req, next) => {
    log("Incoming websocket connection...");

    if (WebSocketHandler.ws) {
        iTender.toggleTare(false);
        WebSocketHandler.ws.close(1001);
    }
    WebSocketHandler.ws = ws;

    await WebSocketHandler.sendRunningConfig();
    await WebSocketHandler.sendContainers();
    await WebSocketHandler.sendStatus();

    async function sendWhenReady() {
        if (iTender.status != iTenderStatus.READY) {
            setTimeout(sendWhenReady, 100);
            return;
        }

        iTender.setStatus(iTenderStatus.REFRESHING);

        let payload = new WebSocketPayload(WebSocketEvent.DRINKS, false, iTender.drinks);
        await WebSocketHandler.send(payload);

        setTimeout(() => {
            if (iTender.status == iTenderStatus.REFRESHING)
                iTender.setStatus(iTenderStatus.READY);
        }, 2000);

    }

    sendWhenReady().then();

    ws.on('message', async (raw, bool) => {
        let msg = WebSocketPayload.parseFromBase64Json(raw);
        // If message is null, close the socket because it could not be decompiled
        if (!msg) {
            ws.close(1011);
            return;
        }

        switch (msg.event) {
            case WebSocketEvent.TARE: {
                if (msg.data["state"] == true) {
                    iTender.toggleTare(true);
                } else {
                    iTender.toggleTare(false);
                }
                break;
            }
            case WebSocketEvent.CONTAINERS: {
                let data = msg.data as { pumpPin: number; sensorType: SensorType; sensor1: number; sensor2: number; volume: number; }[];
                await Container.deleteMany({});

                let i = 0;
                for (let c of data) {
                    let container = new Container();
                    container.slot = i;
                    container.volume = c.volume;
                    container.pumpPin = c.pumpPin;
                    container.sensorType = c.sensorType;
                    container.sensorPin1 = c.sensor1;
                    container.sensorPin2 = c.sensor2;
                    container.enabled = true;
                    container.autoDisabled = true;
                    await container.save();
                    i++;
                }
                break;
            }

            case WebSocketEvent.CONFIG: {
                // ToDo
                // Danach setup modus aus
            }
        }
    });

});

module.exports = router;
