import {
    Component,
    EventEmitter,
    Inject,
    Input,
    OnChanges,
    Output,
    SimpleChanges,
} from '@angular/core';
import { partnersWithRedirect } from '@modules/components/partners-redirect-note/partners-redirect-note.component';
import {
    FlightRequestType,
    ViewType,
} from '@shared/enumerators/flight-request-type.enum';
import { AppSettings } from '@shared/models-legacy';
import { FlightModel, ListItem } from '@shared/models-legacy/flight.model';
import { APP_SETTINGS } from '@shared/services';
import { FeatureFlagsService } from '@shared/services/feature-flags.service';
import { IUrlTimeRange } from '@typings/common/url';
import { ISimpleFlight } from '@typings/flight/flight';
import { findClosestFlight } from './utils/find-closest-flight';

@Component({
    selector: 'online-board-search',
    templateUrl: './online-board-search.component.html',
    styleUrls: ['./online-board-search.component.scss'],
})
export class OnlineBoardSearchComponent implements OnChanges {
    @Input() flights: ListItem<FlightModel>[] = [];
    @Input() partners: string[] = [];
    @Input() searchDate: Date;
    @Input() loading = false;
    @Input() requestType: FlightRequestType;
    @Input() timeFrom: string;
    @Input() timeTo: string;
    @Input() withScrollUp = true;
    @Input() disabledDates: Date[];

    @Output() requestCancel = new EventEmitter<boolean>();
    @Output() searchDateChange = new EventEmitter<Date>();
    @Output() timeRangeChange = new EventEmitter<IUrlTimeRange>();
    @Output() toDetails = new EventEmitter<ISimpleFlight>();

    timeRange: IUrlTimeRange;
    currentFlight: ListItem<FlightModel>;

    FlightRequestType = FlightRequestType;
    ViewType = ViewType;

    constructor(
        public featureFlags: FeatureFlagsService,
        @Inject(APP_SETTINGS) public settings: AppSettings,
    ) {}

    ngOnChanges(changes: SimpleChanges) {
        if ('flights' in changes) {
            if ('loading' in changes) {
                // Queue new macrotasks to let browser rerender after
                // creating flights (long task - about 60ms).
                // After removing populate.logic.ts setTimeout can be removed
                setTimeout(() => {
                    this.setCurrentFlight(this.flights); // about 16ms - if not queued drops frames
                });
            } else {
                //console.log("Got autorefresh flights");
                //console.log(this.currentFlight);
                setTimeout(() => {
                    if (this.currentFlight) {
                        this.flights.forEach((flight) => {
                            if (flight.id === this.currentFlight.id) {
                                flight.expanded = this.currentFlight.expanded;
                                this.currentFlight = flight;
                            }
                        });
                    }
                });
            }
        }

        if ('partners' in changes) {
            setTimeout(() => {
                this.partners = partnersWithRedirect(this.partners);
            });
        }

        if ('timeFrom' in changes || 'timeTo' in changes) {
            this.setTimeRange();
        }
    }

    setCurrentFlight(flights?: ListItem<FlightModel>[]) {
        if (!this.flights) {
            return;
        }

        if (this.currentFlight) {
            this.currentFlight.expanded = false;
        }

        this.currentFlight = findClosestFlight(
            flights,
            this.searchDate,
            this.requestType === FlightRequestType.Arrival,
        );

        if (!this.currentFlight) {
            return;
        }

        this.currentFlight.expanded = true;
    }

    setTimeRange() {
        if (!this.timeFrom || !this.timeTo) {
            this.timeRange = {};
            return;
        }

        this.timeRange = {
            timeFrom: this.timeFrom,
            timeTo: this.timeTo,
        };
    }

    handleDateChanged(date: Date) {
        this.searchDateChange.emit(date);
    }

    handleTimeChanged() {
        this.timeRangeChange.emit(this.timeRange);
    }

    handleToDetailsEvent(flight: ISimpleFlight) {
        this.toDetails.emit(flight);
    }

    handleChangeCurrentFlightEvent(flight: ListItem<FlightModel>) {
        this.currentFlight = flight;
        //console.log("change current flight");
        //console.log(this.currentFlight);
    }

    cancel() {
        this.requestCancel.emit(true);
    }
}
