import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ScheduleSearchDataSourceService } from '@schedule/services/data-source/search-data-source.service';
import { ScheduleNavigationService } from '@schedule/services/navigation.service';
import { ScheduleRequestBuilderService } from '@schedule/services/request/request-builder.service';
import {
    IScheduleRouteDirectionParams,
    IScheduleRouteParams,
} from '@schedule/services/url/types';
import { IScheduleRouteData } from '@schedule/types';
import { IFlight } from '../../../../../typings/flight/flight';
import { StateService } from '@shared/services/state.service';

@Component({
    selector: 'schedule-search',
    templateUrl: './schedule-search-page.component.html',
})
export class ScheduleSearchPageComponent implements OnInit {
    outboundParams: IScheduleRouteDirectionParams;
    inboundParams: IScheduleRouteDirectionParams;

    constructor(
        public dataSource: ScheduleSearchDataSourceService,
        private route: ActivatedRoute,
        private navigationService: ScheduleNavigationService,
        private requestBuilder: ScheduleRequestBuilderService,
        private stateService: StateService,
    ) {}

    ngOnInit() {
        this.route.data.subscribe({
            next: (data: IScheduleRouteData) => {
                if (data.urlParams?.route) {
                    this.handleParamsChange(data.urlParams.route);
                }
            },
        });
    }

    handleSameUrlNavigation() {
        this.dataSource.loadFlightsByRoute(
            this.outboundParams,
            this.inboundParams,
        );
    }

    handleCancellation() {
        this.dataSource.stopLoading();
    }

    handleRouteParamsChange(params: IScheduleRouteDirectionParams) {
        this.navigationService.toRoutePage(params, this.inboundParams);
    }

    handleReturnRouteParamsChange(params: IScheduleRouteDirectionParams) {
        this.navigationService.toRoutePage(this.outboundParams, params);
    }

    handleDetailsEvent(flight: IFlight) {
        const request = this.getRequest();
        this.navigationService.toDetailsPage(flight, request);
    }

    private handleParamsChange(routeParams: IScheduleRouteParams) {
        this.outboundParams = routeParams.outbound;
        this.inboundParams = routeParams.inbound;

        this.stateService.set("schedulein", this.inboundParams);
        this.stateService.set("scheduleout", this.outboundParams);

        this.dataSource.loadFlightsByRoute(
            routeParams.outbound,
            routeParams.inbound,
        );
    }

    private getRequest() {
        if (!this.outboundParams) {
            return undefined;
        }

        return this.requestBuilder.buildRouteRequest(
            this.outboundParams,
            this.inboundParams,
        );
    }
}
