import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';

@Injectable({
    providedIn: 'root'
})
export class SignalrService {
    private hubConnection: signalR.HubConnection | undefined;

    constructor() {
    }

    // public startConnection(): Promise<void> {
    //     this.hubConnection = new signalR.HubConnectionBuilder()
    //         .withUrl('')
    //         .build();

    //     return this.hubConnection
    //         .start()
    //         .then(() => {
    //             console.log('SignalR connection started');
    //         })
    //         .catch(err => console.error('SignalR connection error: ', err));
    // }

    public stopConnection(): Promise<void> {
        return this.hubConnection!
            .stop()
            .then(() => {
                console.log('SignalR connection stopped');
            })
            .catch(err => console.error('Error while stopping SignalR connection: ', err));
    }

    public addDataListener(callback: (data: any) => void): void {
        this.hubConnection!.on('dataReceived', (data) => {
            callback(data);
        });
    }

    public sendData(data: any): Promise<void> {
        return this.hubConnection!.invoke('sendData', data)
            .catch(err => console.error('Error while sending data: ', err));
    }
}