import {SensorType} from "../../SensorType";
import {IContainer} from "../../database/IContainer";
import Container from "../../database/Container";
import {WebSocketPayload} from "../../WebSocketPayload";

export default async function WebsocketContainers<IncomingWebsocketRequest>(msg: WebSocketPayload) {
    let data = msg.data as {
        id?: string,
        pumpPin: number;
        sensorType: SensorType;
        sensor1: number;
        sensor2: number;
        useProxy: boolean
    }[];
    // await Container.deleteMany({}); // V2: Remove this and check every container based on id if changes occurs

    let i = 0;
    for (let c of data) {
        let container: IContainer | null = null;

        if (c.id) {
            container = await Container.findOne({_id: c.id});
        }

        if (!container)
            container = new Container();


        container.slot = i;
        //container.volume = c.volume; // V2: Removed
        container.pumpPin = c.pumpPin;
        container.useProxy = c.useProxy;
        container.sensorType = c.sensorType;
        container.sensorPin1 = c.sensor1;
        container.sensorPin2 = c.sensor2;
        container.enabled = true;
        await container.save();
        i++;
    }

    let containers: IContainer[] = await Container.find();
    for (let c of containers) {
        let find = data.find((e) => {
            return !e.id || c._id == e.id;
        });
        if (!find)
            await Container.deleteOne({_id: c._id});
    }
}