import { Inject, Injectable } from '@angular/core';
import * as signalR from "@microsoft/signalr";
import { environment } from '@environment';
import { interval, Subscription } from 'rxjs';
import { AppSettings } from '@shared/models-legacy';
import { APP_SETTINGS } from '@shared/services';
import { FlightStatus } from '@typings/enums';
import { IOnlineBoardRoutePageUrlParams } from '@online-board/services/url/types';
import { OnlineBoardDataSourceService } from '@online-board/services/data-source.service';
import { IFlightId, IParsedFlightId } from '@typings/flight/flight-id';
import { FadeService } from '@online-board/services/fade.service';

@Injectable()
export class RefreshBoardService {
    connection: any;
    loadParams: IOnlineBoardRoutePageUrlParams;

    constructor(
        @Inject(APP_SETTINGS) private settings: AppSettings,
        public dataSource: OnlineBoardDataSourceService,
        private fadeService: FadeService,
    ) {}

    init() {
        this.connection = new signalR.HubConnectionBuilder()
            .withUrl(environment.urlForTrackerHub)
            .withAutomaticReconnect()
            .build();

        this.connection.on('RefreshDate', (date: string) => {
            this.dataSource.loadFlightsByRoute(this.loadParams, true);
        });

    }

    start(flightDate: string, params: IOnlineBoardRoutePageUrlParams) {
        this.loadParams = params;
        if (!this.connection) {
            this.init();
        }

        // if connection is disconnected then stop just console.log about it and returns, then we start it
        this.connection.stop().then(() => {
            this.fadeService.start();
            this.connection.start().then(() => {
                this.connection.invoke("SubscribeDate", flightDate, params.departure, params.arrival);
            });
        });
    }

    stop() {
        this.connection.stop();
        this.fadeService.stop();
    }
}
