import { Injectable } from '@angular/core'
import { Subject, Observable, Observer } from 'rxjs'
import { webSocket, WebSocketSubject } from 'rxjs/webSocket'

@Injectable()
export class WebsocketService {
    ws: WebSocketSubject<any>

    public connect(url: string, openObserver?: Subject<any>, closeObserver?: Subject<any>) {
        this.ws = webSocket({
            url: url,
            openObserver: openObserver,
            closeObserver: closeObserver
        })
    }

    public disconnect() {
        if (this.ws) {
            this.ws.complete()
        }
    }

    public subscribe(message: string) {
        return this.ws.next('subscribe/' + message)
    }

    public unsubscribe(message: string) {
        return this.ws.next('unsubscribe/' + message)
    }
}