import { isDateStr, compareIsSameOrBefore } from '../../../utils/date';
import { InternalFormFieldValidationRule } from './internal-form-field-validation-rule.abstract';
/**
 * A rule that checks if start date is before than end date
 */
export class DateRangeRule extends InternalFormFieldValidationRule {
  /**
   * If the input is accepted and the status is not disabled and visible, then return true
   *
   * @param {unknown} input - The input to be evaluated.
   * @param {FormFieldStatusMeta} [status] - FormFieldStatusMeta
   * @returns {boolean} A boolean value.
   */
  canEvaluate(input, status) {
    return status
      ? this.isAcceptedInputType(input) && !status.disabled && status.visible
      : this.isAcceptedInputType(input);
  }
  /**
   * If the field is not disabled, visible, and has been touched or modified, then show the error
   *
   * @param {FormFieldStatusMeta} status - FormFieldStatusMeta
   * @returns {boolean} A boolean value.
   */
  shouldShowError(status) {
    return !status.disabled && status.visible && (status.touched || status.modified);
  }
  /**
   * Check if the start date is before than end date
   *
   * @param {string | string[]} input - The value of the date picker.
   * @returns  {EvaluateResultTranslation} - The result of the evaluation.
   */
  evaluate(input) {
    if (!this.isAcceptedInputType(input)) {
      throw new Error(`Unexpected type of input: ${typeof input}: ${input}`);
    }
    const startDate = new Date(input[0]);
    const endDate = new Date(input[1]);
    const isValid = compareIsSameOrBefore(startDate, endDate);
    return {
      isValid: isValid,
      message: isValid ? '' : 'The end date should be later than start date',
    };
  }
  /**
   * If the input is an array of two strings, and each string is a valid date, then return true.
   *
   * @param {unknown} input - The input value to be validated.
   * @returns {boolean} A boolean value.
   */
  isAcceptedInputType(input) {
    return Array.isArray(input) && input.length === 2 && input.every(isDateStr);
  }
}
