import { Injectable } from '@angular/core';
import { IOnlineBoardRoutePageUrlParams } from '@online-board/services/url';
import { StationCodeValidationService } from '@shared/services/validators/station-code.service';
import * as moment from 'moment';

@Injectable()
export class OnlineBoardRouteFilterValidationService {
    dateError: string;
    departureError: string;
    arrivalError: string;

    constructor(private stationValidator: StationCodeValidationService) {}

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

    async validate(params: Partial<IOnlineBoardRoutePageUrlParams>) {
        this.dateError = this.departureError = this.arrivalError = null;

        if (!params.departure && !params.arrival) {
            this.departureError = 'SHARED.DEPARTURE-CITY-ERROR';
            this.arrivalError = 'SHARED.ARRIVAL-CITY-ERROR';

            return false;
        }

        const isDepartureValid = params.departure
            ? await this.stationValidator.isStationCodeValid(params.departure)
            : true;

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

        const isArrivalValid = params.arrival
            ? await this.stationValidator.isStationCodeValid(params.arrival)
            : true;

        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.date || !moment(params.date).isValid()) {
            this.dateError = 'SHARED.DATE_FORMAT-WRONG';
            return false;
        }

        return true;
    }
}
