import { Injectable } from '@angular/core';
import { FlightModel, ScheduleItemModel } from '@shared/models-legacy';
import { theDayAfter, theDayBefore } from '@utils/date';
import * as moment from 'moment';
import { compareFlightsByPId } from '@utils/flight/p-id';

export type IScheduleType =
    | 'empty-schedule'
    | 'default-schedule'
    | 'return-schedule'
    | 'schedule';

@Injectable()
export class ScheduleHelpersService {
    public doesScheduleContainFlight(
        schedule: ScheduleItemModel[] = [],
        flight: FlightModel,
    ) {
        return schedule.some((scheduleItem) => {
            return scheduleItem.flights.some((scheduleFlight) => {
                return compareFlightsByPId(
                    scheduleFlight as any,
                    flight as any,
                );
            });
        });
    }

    public getScheduleType(
        flight?: FlightModel,
        schedule?: ScheduleItemModel[],
        returnSchedule?: ScheduleItemModel[],
    ): IScheduleType {
        if (!flight) {
            return 'empty-schedule';
        }

        if (this.doesScheduleContainFlight(schedule, flight)) {
            return 'schedule';
        }

        if (this.doesScheduleContainFlight(returnSchedule, flight)) {
            return 'return-schedule';
        }

        return 'default-schedule';
    }

    public getDefaultScheduleForFlight(flight: FlightModel) {
        return [
            new ScheduleItemModel({
                date: moment(flight.dateToSearchBy).startOf('day').toDate(),
                flights: [flight],
            }),
        ];
    }

    public getFirstScheduleDayToAdd(schedule: ScheduleItemModel[]) {
        const [firstDay] = schedule;
        const scheduleToAddDate = theDayBefore(firstDay.date);

        return ScheduleHelpersService.getEmptyScheduleItem(scheduleToAddDate);
    }

    public getLastScheduleDayToAdd(schedule: ScheduleItemModel[]) {
        const lastDaySchedule = schedule[schedule.length - 1];
        const scheduleToAddDate = theDayAfter(lastDaySchedule.date);

        return ScheduleHelpersService.getEmptyScheduleItem(scheduleToAddDate);
    }

    private static getEmptyScheduleItem(date: Date) {
        return new ScheduleItemModel({
            date: date,
            flights: [],
        });
    }
}
