import { forwardRef, Inject, Injectable, OnDestroy } from '@angular/core';
import { PecoTsWebSocket } from '@pecometer/pecots-websocket-client';
import { Window } from './window';

@Injectable()
export class WebSocket implements OnDestroy {
    private _endPoint: string = '';
    private _socket: PecoTsWebSocket = null;

    constructor(@Inject(forwardRef(() => Window)) private _window: Window) {
        if (process.env.SSL) {
            this._endPoint = `wss://${this._window.nativeWindow.location.hostname}`;
            if (this._window.nativeWindow.location.port !== '443') {
                this._endPoint += this._window.nativeWindow.location.port;
            }
        } else {
            this._endPoint = `ws://${this._window.nativeWindow.location.hostname}`;
            if (process.env.NODE_ENV === 'development') {
                this._endPoint += `:4444`;
            }
        }
        this._socket = new PecoTsWebSocket();
    }

    // Initialises the websocket - should only be called by a once a user is logged in
    public init(token: string) {
        this._socket.init(this._endPoint, token);
    }

    public ngOnDestroy() {
        this._socket.disconnect();
    }

    // Registers a new event listener to the socket
    public register(event: string) {
        return this._socket.register(event);
    }

    public disconnect() {
        this._socket.disconnect();
    }
}
