import {WebSocketPayload} from "./WebSocketPayload";
import {WebSocketEvent} from "./WebSocketEvent";
import {iTender} from "./iTender";
import {Settings} from "./Settings";
import Container from "./database/Container";

export class WebSocketHandler {
    private static _ws: WebSocket;

    static get ws(): WebSocket {
        return this._ws;
    }

    static set ws(value: WebSocket) {
        this._ws = value;
    }

    public static send(payload: WebSocketPayload): Promise<void> {
        return new Promise(async (resolve, reject) => {
            try {
                if (this.ws && this.ws.readyState == 1) {
                    await this.ws.send(payload.toString());
                    resolve();
                }
            } catch (e) {

            }
        });
    }

    public static sendStatus() {
        return new Promise(resolve => {
            let payload = new WebSocketPayload(WebSocketEvent.STATUS, false, {status: iTender.status});
            WebSocketHandler.send(payload).then(resolve);
        });
    }

    static sendRunningConfig() {
        return new Promise(resolve => {
            let payload = new WebSocketPayload(WebSocketEvent.CONFIG, false, Settings.json);
            WebSocketHandler.send(payload).then(resolve);
        })
    }

    static sendContainers() {
        return new Promise(async resolve => {
            let payload = new WebSocketPayload(WebSocketEvent.CONTAINERS, false, ( await Container.find() ));
            WebSocketHandler.send(payload).then(resolve);
        })
    }
}