// Copyright 2020 Thomas Hintz
//
// This file is part of the Alpha Centauri Farming project.
//
// The Alpha Centauri Farming project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General
// Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// The Alpha Centauri Farming project is distributed in the hope that
// it will be useful, but WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.  See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the Alpha Centauri Farming project.  If not, see
// <https://www.gnu.org/licenses/>.

export { sendCommand, setMainOnMessage, setSecondaryOnMessage,
         setMainOnOpen, openMain, openSecondary,
         closeMain, closeSecondary }

class WebSocketConnection {
    location = '';
    fullPath = '';
    reopen = true;
    onmessageProc = () => 'nothing'
    ws = null;

    constructor(location) {
        this.location = location;
        const loc = window.location;
        let uri = '';
        if (loc.protocol === "https:") {
            uri = "wss:";
        } else {
            uri = "ws:";
        }
        uri += "//" + loc.host;
        this.fullPath = uri + '/websocket/' + location;
        this.ws = new WebSocket(uri + '/websocket/' + location);
    }

    close() {
        this.reopen = false;
        this.ws.close();
    }

    sendCommand(cmd) {
        this.ws.send(JSON.stringify(cmd));
    }

    reestablish = () => {
        this.ws = new WebSocket(this.fullPath);
        this.ws.onmessage = this.onmessageProc;
    }

    onmessage(proc) {
        this.onmessageProc = proc;
        this.ws.onmessage = proc;
        // this.ws.onclose = () => {
        //     setTimeout(this.reestablish, 500);
        // }
    }

    onopen(proc) {
        this.ws.onopen = proc;
    }
}

var ws;
var ws2;

function openMain(location) {
    ws = new WebSocketConnection(location);
}

function openSecondary(location) {
    ws2 = new WebSocketConnection(location);
}

function closeMain() {
    ws.close();
}

function closeSecondary() {
    ws2.close();
}

function sendCommand(cmd) {
    ws.sendCommand(cmd);
}

function setMainOnMessage(proc) {
    ws.onmessage(proc);
}

function setSecondaryOnMessage(proc) {
    ws2.onmessage(proc);
}

function setMainOnOpen(proc) {
    ws.onopen(proc);
}
