import {
    ChangeDetectionStrategy,
    Component,
    EventEmitter,
    Input,
    Output,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FlightModel } from '@shared/models-legacy';
import { ListItem } from '@shared/models-legacy/flight.model';
import { RouteTypeLegacy } from '@app/shared/enumerators';
import { Destroyable } from '@app/shared/destroyable';
import { ISimpleFlight } from '@typings/flight/flight';
import { takeUntil } from 'rxjs/operators';

@Component({
    selector: 'board-search-result',
    templateUrl: './board-search-result.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BoardSearchResultComponent extends Destroyable {
    flightDateFilter: string;
    @Input() flights: ListItem<FlightModel>[];
    @Input() currentFlight: ListItem<FlightModel>;

    @Output() toDetails = new EventEmitter<ISimpleFlight>();
    @Output() changeCurrentFlight = new EventEmitter<ListItem<FlightModel>>();

    constructor(private route: ActivatedRoute) {
        super();
        this.route.params.pipe(takeUntil(this.destroy$)).subscribe((params) => {
            this.flightDateFilter = params['flightDate'];
        });
    }
    RouteType = RouteTypeLegacy;

    trackByHash(_: number, flight: FlightModel) {
        return flight.hash;
    }

    ngOnDestroy(): void {
        super.ngOnDestroy();
    }

    onTabOpen(e) {
        // refresh flight
    }

    toggle(index: number) {
        const flight = this.flights[index];

        if (!flight) return;

        if (this.currentFlight == flight) {
            flight.expanded = !flight.expanded;
            return;
        }

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

        this.currentFlight = flight;
        this.changeCurrentFlight.emit(flight);
    }

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