import { Injectable } from '@angular/core';
import { StationCodeValidationService } from '@shared/services/validators/station-code.service';
import { OnlineBoardNavigationService } from '@online-board/services/navigation.service';
import { IOnlineBoardRoutePageUrlParams } from '@online-board/services/url/types';
import { CanActivate } from '@angular/router';
import { CanActivateRedirrect } from './can-activate-redirrect-to-not-found';

type IStations = Pick<IOnlineBoardRoutePageUrlParams, 'arrival' | 'departure'>;

@Injectable()
export class CanActivateStations {
    constructor(
        private stationValidator: StationCodeValidationService,
        private navigationService: OnlineBoardNavigationService,
        private canRedirrect: CanActivateRedirrect,
    ) {}

    public async canActivate(stations: IStations) {
        let validationResult = await this.validateStations(stations);

        validationResult = validationResult && this.canRedirrect.validateStation(stations.departure) && this.canRedirrect.validateStation(stations.arrival);

        return validationResult ? true : this.navigationService.toNotFound();
    }

    public async validateStations(stations: IStations) {
        if (!stations.arrival && !stations.departure) {
            return false;
        }

        let isArrivalValid = true;
        let isDepartureValid = true;

        if (stations.arrival) {
            isArrivalValid = await this.stationValidator.isStationCodeValid(
                stations.arrival,
            );
        }

        if (stations.departure) {
            isDepartureValid = await this.stationValidator.isStationCodeValid(
                stations.departure,
            );
        }

        return !(!isArrivalValid || !isDepartureValid);
    }
}
