import { Injectable } from '@angular/core';
import { AppSettingsService } from '@shared/services';
import { isBetween, isSameOrBefore } from '@utils/date';

@Injectable()
export class ScheduleDateValidationService {
    constructor(private settings: AppSettingsService) {}

    isDateValid(date: Date) {
        return this.settings
            .getSettings()
            .then(({ scheduleMinDate, scheduleMaxDate }) => {
                return isBetween(date, scheduleMinDate, scheduleMaxDate);
            });
    }

    /**
     * Checks if provided date is valid.
     * If it isn't, returns minimum schedule date.
     * Otherwise, returns date.
     * */
    getMinValidDate(date?: Date) {
        if (!date) {
            return Promise.resolve(undefined);
        }

        return this.settings.getSettings().then(({ scheduleMinDate }) => {
            return isSameOrBefore(scheduleMinDate, date)
                ? date
                : scheduleMinDate;
        });
    }

    /**
     * Checks if provided date is valid.
     * If it isn't, returns maximum schedule date.
     * Otherwise, returns date.
     * */
    getMaxValidDate(date?: Date) {
        if (!date) {
            return Promise.resolve(undefined);
        }

        return this.settings.getSettings().then(({ scheduleMaxDate }) => {
            return isSameOrBefore(date, scheduleMaxDate)
                ? date
                : scheduleMaxDate;
        });
    }
}
