import { Inject, Injectable } from '@angular/core';
import * as signalR from "@microsoft/signalr";
import { environment } from '@environment';
import { AppSettings } from '@shared/models-legacy';
import { APP_SETTINGS } from '@shared/services';
import { FlightStatus } from '@typings/enums';
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 RefreshService {
    connection: any;

    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('Refresh', (flightId: string) => {
            const l = flightId.length;
            const params: IParsedFlightId = {
                carrier: flightId.substring(0,2),
                flightNumber: flightId.substring(2,6),
                suffix: flightId.substring(6,l-11),
                date: new Date(flightId.substring(l-10, l)),
            };
            this.dataSource.loadFlightByFlightNumber(params, true).finally(() => {
            });;
        });
    }

    start(params: IFlightId) {
        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("Subscribe", params.carrier+params.flightNumber+params.suffix+"@"+params.dateLT);
            });
        });
    }

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