import { Injectable } from '@angular/core';
import { IOnlineBoardRoutePageUrlParams } from '@online-board/services/url/types';
import { CanActivateDateParams } from './can-activate-date-params';
import { CanActivateStations } from './can-activate-stations';
import { CanActivateRedirrect } from './can-activate-redirrect-to-not-found';
import { OnlineBoardNavigationService } from '../../services/navigation.service';

@Injectable()
export class CanActivateRouteParams {
    constructor(
        private stationsService: CanActivateStations,
        private dateParamsService: CanActivateDateParams,
        private canRedirrect: CanActivateRedirrect,
        private navigationService: OnlineBoardNavigationService,
    ) {}

    public async canActivate(params: IOnlineBoardRoutePageUrlParams) {

        if (!this.canRedirrect.validateStation(params.arrival) || !this.canRedirrect.validateStation(params.departure)) {
            return this.navigationService.toNotFound();
        }

        const canActivateStations = await this.stationsService.canActivate(
            params,
        );

        if (canActivateStations !== true) {
            return canActivateStations;
        }

        if (!params.date || !this.canRedirrect.validateTimeRange(params.timeFrom, params.timeTo)) {
            return this.navigationService.toNotFound();
        }

        const canActivateDateParams = await this.dateParamsService.canActivate(
            params,
        );

        if (canActivateDateParams !== true) {
            return canActivateDateParams;
        }

        return true;
    }

    public async validateRouteParams(params: IOnlineBoardRoutePageUrlParams) {
        const canActivateStations = await this.stationsService.validateStations(
            params,
        );

        const canActivateDateParams =
            await this.dateParamsService.validateDateParams(params);

        return canActivateDateParams && canActivateStations;
    }
}
