import {
    Component,
    EventEmitter,
    Input,
    OnChanges,
    Output,
    SimpleChanges,
} from '@angular/core';
import { ScheduleItemModel, ScheduleSortMode } from '@shared/models-legacy';
import { ScheduleStateService } from '@schedule/services/state.service';
import { IFlight } from '../../../../../../../typings/flight/flight';
import * as moment from 'moment';

@Component({
    selector: 'schedule-days',
    templateUrl: './schedule-days.component.html',
})
export class ScheduleDaysComponent implements OnChanges {
    @Input() schedule: ScheduleItemModel[];
    @Input() isDirect: boolean;
    @Input() sortBy: ScheduleSortMode;
    @Output() toDetails = new EventEmitter<IFlight>();

    constructor(private state: ScheduleStateService) {}

    onTabOpen({ index }: { index: number }) {
        const schedule = this.schedule[index];

        this.expandDefaultFlight(schedule);
    }

    getScrollDelay(index: number) {
        const DELAY_PER_HUNDRED_FLIGHTS = 500;
        if (index === 0) {
            return 0;
        }

        const flightsNumber = this.schedule[index].flights.length;

        return Math.ceil(flightsNumber / 100) * DELAY_PER_HUNDRED_FLIGHTS;
    }

    private expandDefaultGroup() {
        const byDate = (date: Date) =>
            this.schedule.find((i) => moment(i.date).isSame(date, 'day'));
        const byState = () => byDate(this.state.selectedDate);
        const byToday = () => byDate(new Date());
        const byNonEmpty = () => this.schedule.find((i) => !!i.flights.length);

        for (const fn of [byState, byToday, byNonEmpty]) {
            const group = fn();

            if (!group) {
                continue;
            }

            group.expanded = true;
            this.expandDefaultFlight(group);
            break;
        }
    }

    private expandDefaultFlight(group?: ScheduleItemModel) {
        const [flight] = group?.flights || [];
        if (!flight) {
            return;
        }
        flight.expanded = true;
    }

    ngOnChanges(changes: SimpleChanges) {
        if (this.schedule && 'schedule' in changes) {
            this.expandDefaultGroup();
        }
    }

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