import { UntypedFormGroup } from '@angular/forms';
import { Dayjs } from 'dayjs';

export function applyIntervalConstraints(
    value,
    previousFrom: Dayjs,
    previousTo: Dayjs,
    form: UntypedFormGroup,
    fromKey: string,
    toKey: string,
): boolean {
    if (!!value[fromKey] && !!value[toKey]) {
        if (previousFrom !== value[fromKey]) {
            if (value[toKey].isBefore(value[fromKey])) {
                form.patchValue({ [toKey]: value[fromKey] });
                return true;
            }
        } else if (previousTo !== value[toKey]) {
            if (value[toKey].isBefore(value[fromKey])) {
                form.patchValue({ [fromKey]: value[toKey] });
                return true;
            }
        }
    }
    return false;
}
