import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { OnlineBoardDataSourceService } from '@online-board/services/data-source.service';
import { OnlineBoardNavigationService } from '@online-board/services/navigation.service';
import { OnlineBoardRequestBuilderService } from '@online-board/services/request/request-builder.service';
import { IOnlineBoardRoutePageUrlParams } from '@online-board/services/url/types';
import { OnlineBoardApiService } from '@online-board/services/api.service';
import { OnlineBoardRouteFilterValidationService } from '@online-board/components/filter/components/route-filter/services/online-board-route-filter-validation.service';
import { FlightRequestType } from '@shared/enumerators/flight-request-type.enum';
import { IUrlTimeRange } from '@typings/common/url';
import { ISimpleFlight } from '@typings/flight/flight';
import { IOnlineBoardRouteData } from '@online-board/types';
import { RefreshBoardService } from './services/refresh-board.service';
import { ApiFormatterService } from '@shared/services/api/formatter.service';
import FlightDateUtils from '@utils/flight/date';

@Component({
    selector: 'online-board-search-page-base',
    templateUrl: './search-page-base.component.html',
    providers: [OnlineBoardRouteFilterValidationService, RefreshBoardService],
})
export class OnlineBoardSearchPageBaseComponent implements OnInit {
    @Input() requestType: FlightRequestType;
    disabledDates: Date[];

    params: IOnlineBoardRoutePageUrlParams;

    constructor(
        public dataSource: OnlineBoardDataSourceService,
        private apiService: OnlineBoardApiService,
        private apiFormatter: ApiFormatterService,
        private validationService: OnlineBoardRouteFilterValidationService,
        private route: ActivatedRoute,
        private refreshBoardService: RefreshBoardService,
        private navigationService: OnlineBoardNavigationService,
        private requestBuilder: OnlineBoardRequestBuilderService,
    ) {}

    ngOnInit(): void {
        this.route.data.subscribe({
            next: (data: IOnlineBoardRouteData) => {
                if (data.urlParams?.route) {
                    this.params = data.urlParams.route;

                    this.dataSource.loadFlightsByRoute(this.params);
                    this.refreshBoardService.start(this.apiFormatter.formatDateOnly(this.params.date), this.params);
                }
                this.updateCalendar();
            },
        });
    }

    ngOnDestroy() {
        this.refreshBoardService.stop();
    }

    async updateCalendar() {
        const isDepartureValid = await this.validationService.validateCode(this.params.departure);
        const isArrivalValid = await this.validationService.validateCode(this.params.arrival);

        if (isDepartureValid || isArrivalValid) {
            var date = new Date();
            date.setUTCHours(0,0,0,0);
            date.setDate(date.getDate() - 1);
            this.apiService
                .getFlightDaysByRoute(date, isDepartureValid ? this.params.departure: undefined, isArrivalValid ? this.params.arrival: undefined)
                .then((res) => {
                    this.disabledDates = new Array();
                    for(var i=0;i<res.days.length;i++) {
                        if (res.days[i] == '0') {
                            this.disabledDates.push(new Date(date));
                        }
                        date.setDate(date.getDate() + 1);
                    }
                })
                .finally(() => {
                });
        } else {
            this.disabledDates = new Array();
        }
    }


    public handleSameUrlNavigation() {
        this.dataSource.loadFlightsByRoute(this.params);
    }

    public handleRequestCancellation() {
        this.dataSource.stopLoading();

        return this.navigationService.toStartPage();
    }

    public handleDateChange(date: Date) {
        return this.navigationService.toRoutePage({
            ...this.params,
            date,
        });
    }

    public handleTimeRangeChange(timeRange?: IUrlTimeRange) {
        return this.navigationService.toRoutePage({
            ...this.params,
            timeFrom: timeRange?.timeFrom,
            timeTo: timeRange?.timeTo,
        });
    }

    public navigateToDetails(flight: ISimpleFlight) {
        const request = this.requestBuilder.buildRouteRequest(this.params);

        return this.navigationService.toDetailsPage({
            flightId: flight.flightId,
            date: FlightDateUtils.getFlightDate(flight),
            request,
        });
    }
}
