import { Injectable } from '@angular/core';
import { ScheduleApiService } from '@schedule/services/api.service';
import { ScheduleDateValidationService } from '@schedule/services/date-validation.service';
import { IScheduleDetailsParams } from '@schedule/services/url/types';
import { FlightModel } from '@shared/models-legacy';
import PopulateLogicLegacy from '@shared/models-legacy/populate.logic';
import { FlightStatus, RouteType } from '@typings/enums';
import { IFlight, ISimpleFlight } from '@typings/flight/flight';
import { RouteTypeLegacy } from '@shared/enumerators';
import { ScheduleSearchDataSourceService } from './search-data-source.service';

@Injectable()
export class ScheduleDetailsDataSourceService extends ScheduleSearchDataSourceService {
    private _flights: ISimpleFlight[];
    private _flightsLegacy: FlightModel[] = [];
    private _detailsLoading = false;
    private _disabledDates: Date[];

    constructor(
        protected apiService: ScheduleApiService,
        protected dateValidator: ScheduleDateValidationService,
    ) {
        super(apiService, dateValidator);
    }

    get disabledDates() {
        return this._disabledDates;
    }

    get flights() {
        return this._flights;
    }

    get flight(): IFlight | undefined {
        if (!this.flights || !this.flights.length) {
            return undefined;
        }

        if (this.flights.length > 1) {
            return {
                routeType: RouteType.CONNECTING,
                flights: this.flights,
                flyingTime: '', //todo compute flyingTime from flights
                status: FlightStatus.SCHEDULED,
            };
        }

        return this.flights[0];
    }

    get flightLegacy(): FlightModel {
        if (this.flightsLegacy.length > 1) {
            return {
                routeType: RouteType.CONNECTING,
                flights: this.flightsLegacy,
                dateToSearchBy: this.flightsLegacy[0].dateToSearchBy,
                lastUpdate: this.flightsLegacy[0].lastUpdate,
            } as any;
        }

        return this.flightsLegacy[0];
    }

    get flightsLegacy() {
        return this._flightsLegacy;
    }

    get detailsLoading() {
        return this._detailsLoading;
    }

    public loadFlightDetails(params: IScheduleDetailsParams) {
        const flightsInfo = params.flights.map((flightParams) => {
            return `${flightParams.carrier}${flightParams.flightNumber}${flightParams.suffix}`+(flightParams.departure? '-'+flightParams.departure+flightParams.arrival : '');
        });
        const departure = params.flights[0].departure ?? params.departure;
        const arrival = params.flights[params.flights.length-1].arrival ?? params.arrival;

        const dates = params.flights.map((flightParams) => {
            return flightParams.date;
        });

        this._detailsLoading = true;

        //console.log('service: ', this);
        return this.apiService
            .getFlightDetails(flightsInfo, dates, departure, arrival)
            .then((res) => {
                this._flights = res.data.routes;
                var days = new Set<string>();
                for(var d in res.data.daysOfFlight) {
                    days.add(res.data.daysOfFlight[d]);
                }
                var date = new Date();
                date.setUTCHours(0,0,0,0);
                date.setDate(date.getDate() - 1);
                this._disabledDates = new Array();
                for(var i=0;i<367;i++) {
                    var d = [
                        date.getFullYear(),
                        ('0' + (date.getMonth() + 1)).slice(-2),
                        ('0' + date.getDate()).slice(-2)
                    ].join('');
                    if (!days.has(d)) {
                        this._disabledDates.push(new Date(date));
                    }
                    date.setDate(date.getDate() + 1);
                }

                this._flightsLegacy = PopulateLogicLegacy.createFlights(
                    res.data.routes as any,
                );

                this.addCrossIndexToLegacyFlightsLegs();
            })
            .finally(() => {
                this._detailsLoading = false;
            });
    }

    private addCrossIndexToLegacyFlightsLegs() {
        if (this._flightsLegacy.length > 1) {
            const legs = this._flightsLegacy.reduce((result, flight) => {
                if (flight.routeType === RouteTypeLegacy.Direct) {
                    result.push(flight.leg);
                } else {
                    result = [...result, ...flight.legs];
                }

                return result;
            }, []);

            legs.forEach((leg, index) => {
                leg.crossIndex = index + 1;
            });
        }
    }
}
