import {
    ChangeDetectionStrategy,
    Component,
    EventEmitter,
    Input,
    OnChanges,
    OnInit,
    Output,
} from '@angular/core';
import {
    FlightModel,
    ListItem,
    ScheduleItemModel,
    ScheduleSortMode,
} from '@shared/models-legacy';
import { RouteTypeLegacy } from '@app/shared/enumerators';
import { sortFlights } from '@shared/pipes-legacy/sort-flights-by.pipe';
import { IFlight } from '@typings/flight/flight';

@Component({
    selector: 'list-scheduled-flight',
    templateUrl: './list-scheduled-flight.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ListScheduledFlightComponent implements OnInit, OnChanges {
    @Input() scheduleItem: ScheduleItemModel;
    @Input() sortBy: ScheduleSortMode;
    @Output() toDetails = new EventEmitter<IFlight>();

    flight: ListItem<FlightModel>;
    flights: ListItem<FlightModel>[];

    RouteType = RouteTypeLegacy;

    expanded: boolean;

    ngOnInit() {
        this.flight = this.scheduleItem.flights[0];
    }

    ngOnChanges(changes) {
        if ('scheduleItem' in changes) {
            this.flights = this.scheduleItem.flights.slice();
        }

        if ('sortBy' in changes) {
            sortFlights(this.flights, this.sortBy);
        }
    }

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

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

        if (!flight) return;

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

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

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