import { Inject, Injectable } from '@angular/core';
import { airlines } from '@app/shared/airlines';
import { OperationStatusLegacy } from '@app/shared/enumerators';
import { FlightModel, getFirstLeg, getFlights } from '@app/shared/models-legacy';
import { WINDOW } from '@app/shared/services';

@Injectable({ providedIn: 'root' })
export class RegistrationLogic {
    constructor(@Inject(WINDOW) private window$: any) {}
    operatingMap = new Map(airlines.filter((a) => a.canRegister).map((a) => [a.code, a.registrationUrl]));

    isAnyAvailable(flight: FlightModel) {
        return !getFlights(flight).some((f) => !this.isOneAvailable(f));
    }
    isOneAvailable(flight: FlightModel) {
        return !!this.getKey(flight) && this.isOpen(flight);
    }
    isOpen(flight: FlightModel) {
        return getFirstLeg(flight).transition?.registration?.status === OperationStatusLegacy.inProgress;
    }
    getKey(flight: FlightModel) {
        const key = flight.operatingBy?.actual || flight.operatingBy?.scheduled;
        return this.operatingMap.get(key);
    }
    goto(flight: FlightModel) {
        getFlights(flight).forEach((flight) => {
            if (!this.isOneAvailable(flight)) return;
            this.window$.open(this.getKey(flight));
        });
    }
}
