"use strict";

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

class websocket {
    _echo = null;
    pusher = Pusher;

    callbacks = []

    constructor() {
        let _this = this;
        axios.get('/websockets/settings')
            .then(response => {
                _this._echo = new Echo({
                    broadcaster: 'reverb',
                    key: response.data.key,
                    wsHost: response.data.wsHost,
                    wsPort: response.data.wsPort,
                    wssPort: response.data.wssPort,
                    forceTLS: response.data.forceTLS,
                    enabledTransports: ['ws', 'wss'],
                });
                _this.startCallbacks();
            })
            .catch(error => {

            });
    }

    add(callback) {
        if (this._echo !== null) {
            callback(this._echo)
            return ;
        }

        this.callbacks.push(callback);
    }

    startCallbacks() {
        let _this = this;
        this.callbacks.forEach(function(callback) {
            callback(_this._echo)
        });
    }
}

window.websocket = new websocket();
