import { Injectable } from '@angular/core';
import {
    theDayBefore as getDayBefore,
    theDayAfter as getDayAfter,
    isBetween,
    getStartOfTheWeek,
    getEndOfTheWeek,
} from '@utils/date';
import { IScheduleDateParams } from '@schedule/services/url/types';
import { AppSettingsService } from '@shared/services';
import { ScheduleDateValidationService } from '@schedule/services/date-validation.service';

@Injectable()
export class DetailsScheduleDatesService {
    constructor(
        private settings: AppSettingsService,
        private datesService: ScheduleDateValidationService,
    ) {}

    /**
     * returns dates range for mini list.
     * It should span maximum three days.
     * If first or third day exceeds
     * schedule search limit, thees days
     * will be discarded.
     * */
    public async getMiniListDatesRange(
        flightDate: Date,
    ): Promise<Omit<IScheduleDateParams, 'timeFrom' | 'timeTo'>> {
        const theDayBefore = getDayBefore(flightDate);
        const theDayAfter = getDayAfter(flightDate);

        const { scheduleMaxDate, scheduleMinDate } =
            await this.settings.getSettings();

        const validDates = [theDayBefore, flightDate, theDayAfter].filter(
            (date) => {
                return isBetween(date, scheduleMinDate, scheduleMaxDate);
            },
        );

        return {
            dateFrom: validDates[0],
            dateTo: validDates[validDates.length - 1],
        };
    }

    public async getScheduleDatesRange(
        flightDate: Date,
    ): Promise<Omit<IScheduleDateParams, 'timeFrom' | 'timeTo'>> {
        const startOfTheWeek = getStartOfTheWeek(flightDate);
        const endOfTheWeek = getEndOfTheWeek(flightDate);

        const dateFrom = await this.datesService.getMinValidDate(
            startOfTheWeek,
        );
        const dateTo = await this.datesService.getMaxValidDate(endOfTheWeek);

        return {
            dateFrom,
            dateTo,
        };
    }
}
