import { Injectable } from '@angular/core';
import { OnlineBoardDateValidationService } from '@online-board/services/date-validation.service';
import { OnlineBoardNavigationService } from '@online-board/services/navigation.service';
import { IOnlineBoardUrlDateParams } from '@online-board/services/url/types';
import { TimeRangeValidationService } from '@shared/services/validators/time-range.service';
import { CanActivateRedirrect } from './can-activate-redirrect-to-not-found';

@Injectable()
export class CanActivateDateParams {
    constructor(
        private dateValidator: OnlineBoardDateValidationService,
        private timeRangeValidator: TimeRangeValidationService,
        private navigationService: OnlineBoardNavigationService,
        private canRedirrect: CanActivateRedirrect,
    ) {}

    public async canActivate(params: IOnlineBoardUrlDateParams) {
        const validationResult = await this.validateDateParams(params);

        const isTimeRangeValid = this.canRedirrect.validateTimeRange(params.timeFrom, params.timeTo);

        if (!isTimeRangeValid || !params.date) {
            return this.navigationService.toNotFound();
        }

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

    public async validateDateParams(params: IOnlineBoardUrlDateParams) {
        const isDateValid = await this.dateValidator.isDateValid(params.date);

        const isTimeRangeValid = this.timeRangeValidator.isTimeRangeValid(
            params.timeFrom,
            params.timeTo,
        );

        return !(!isDateValid || !isTimeRangeValid);
    }
}
