import { Pipe, PipeTransform } from '@angular/core';
import { ViewType } from '@app/shared/enumerators/flight-request-type.enum';
import { FlightModel, getFirstLeg, getFlights, getLastLeg } from '@app/shared/models-legacy';
import { TranslatePipe } from '@ngx-translate/core';

@Pipe({
    name: 'flightTitle',
})
export class FlightTitlePipe implements PipeTransform {
    constructor(private translatePipe: TranslatePipe) {}

    private translate(value: string) {
        return this.translatePipe.transform(value);
    }

    transform(flights?: FlightModel | FlightModel[], type: ViewType = ViewType.Onlineboard): string {
        if (!flights) return '';

        if (!Array.isArray(flights)) flights = [flights];
        if (!flights.length) return;

        flights = flights
            .map((f) => getFlights(f))
            .reduce((a, c) => a.concat(c))
            .filter((f) => !!f.flightId);

        const from = getFirstLeg(flights[0]).departure;
        const to = getLastLeg(flights[flights.length - 1]).arrival;

        const many = flights.length > 1;

        if (!from || !to) return '';

        const departure = from.latest || from.scheduled;
        const arrival = to.latest || from.scheduled;
        const flightNumber = flights.map((f) => `${f.flightId.carrier}\u00a0${f.flightId.flightNumber}`).join(', ');

        if (type === ViewType.Onlineboard) {
            const prefix = many ? this.translate('SHARED.FLIGHTS-INFO') : this.translate('SHARED.FLIGHT-INFO');

            return `${prefix}: ${flightNumber}, ${departure.city} - ${arrival.city}`;
        }

        if (type === ViewType.Schedule) {
            const prefix = many ? this.translate('SCHEDULE.SCHEDULE-FLIGHTS') : this.translate('SHARED.SCHEDULE-FLIGHT');

            return many ? `${prefix}: ${flightNumber}` : `${prefix}: ${flightNumber}, ${departure.city} - ${arrival.city}`;
        }

        return '';
    }
}
