"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Holder_1 = require("../../../../../Class/Holder");
const Socket_1 = require("../../../../../wrap/Socket");
const _ids_1 = require("../../../../_ids");
class Socket extends Holder_1.Holder {
    constructor(system) {
        super({
            fi: ['url'],
            fo: ['channel'],
            i: [],
            o: [],
        }, {
            output: {
                channel: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_SOCKET, 'close');
        this._web_socket = null;
    }
    f({ url }, done) {
        if (this._web_socket) {
            this._web_socket.close();
        }
        try {
            this._web_socket = new WebSocket(url);
        }
        catch (err) {
            if (err.message ===
                "Failed to construct 'WebSocket': The URL '' is invalid.") {
                done(undefined, 'malformed url');
            }
            else {
                done(undefined, err.message.toLowerCase());
            }
            return;
        }
        const channel = (0, Socket_1.wrapWebSocket)(this._web_socket, this.__system);
        this._web_socket.onopen = () => {
            done({ channel });
        };
        this._web_socket.onmessage = (message) => {
            channel.emit('message', message.data);
        };
        this._web_socket.onerror = (event) => {
            done(undefined, 'could not connect');
        };
        this._web_socket.onclose = (event) => {
            const { code, reason } = event;
            channel.emit('close', code, reason);
        };
    }
    d() {
        if (this._web_socket) {
            if (this._web_socket.readyState === WebSocket.OPEN) {
                this._web_socket.close();
            }
            this._web_socket.onopen = null;
            this._web_socket.onmessage = null;
            this._web_socket.onerror = null;
            this._web_socket.onclose = null;
            this._web_socket = null;
        }
    }
    async send(data) {
        if (this._web_socket) {
            if (this._web_socket.readyState === WebSocket.OPEN) {
                this._web_socket.send(data);
            }
        }
    }
}
exports.default = Socket;
//# sourceMappingURL=index.js.map