import { Injectable } from '@angular/core';
import {
    IScheduleRouteDirectionParams,
    IScheduleRouteParams,
} from '@schedule/services/url/types';
import { StationCodeValidationService } from '@shared/services/validators/station-code.service';
import * as moment from 'moment';

@Injectable()
export class ScheduleFilterValidationService {
    arrivalError: string | undefined;
    departureError: string | undefined;
    dateRangeError: string | undefined;
    returnDateRangeError: string | undefined;

    constructor(private stationValidator: StationCodeValidationService) {}

    async validateCode(code: string) {
        return this.stationValidator.isStationCodeValid(code);
    }

    async validate(params: IScheduleRouteParams) {
        this.clear();

        return Promise.all([
            this.validateOutboundParams(params.outbound),
            this.validateInboundParams(params.inbound),
        ]).then((res) => res.every(Boolean));
    }

    private async validateOutboundParams(
        params: Partial<IScheduleRouteDirectionParams>,
    ) {
        const isDepartureValid =
            params.departure &&
            (await this.stationValidator.isStationCodeValid(params.departure));

        if (!isDepartureValid) {
            this.departureError = 'SHARED.DEPARTURE-CITY-ERROR';
            return false;
        }

        const isArrivalValid =
            params.arrival &&
            (await this.stationValidator.isStationCodeValid(params.arrival));

        if (!isArrivalValid) {
            this.arrivalError = 'SHARED.ARRIVAL-CITY-ERROR';
            return false;
        }

        if (params.departure === params.arrival) {
            this.departureError = 'SHARED.ARRIVAL-EQUALS-DEPARTURE-ERROR';
            return false;
        }

        if (!params.dateFrom || !moment(params.dateFrom).isValid()) {
            this.dateRangeError = 'SHARED.WEEK_FORMAT-WRONG';
            return false;
        }

        if (!params.dateTo || !moment(params.dateTo).isValid()) {
            this.dateRangeError = 'SHARED.WEEK_FORMAT-WRONG';
            return false;
        }

        return true;
    }

    private validateInboundParams(params?: IScheduleRouteDirectionParams) {
        if (!params) {
            return true;
        }

        if (!params.dateFrom || !moment(params.dateFrom).isValid()) {
            this.returnDateRangeError = 'SHARED.WEEK_FORMAT-WRONG';
            return false;
        }

        if (!params.dateTo || !moment(params.dateTo).isValid()) {
            this.returnDateRangeError = 'SHARED.WEEK_FORMAT-WRONG';
            return false;
        }

        return true;
    }

    private clear() {
        this.arrivalError = undefined;
        this.departureError = undefined;
        this.dateRangeError = undefined;
        this.returnDateRangeError = undefined;
    }
}
