var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { VegaSlimmer, MapToComponentField, MapToComponentMethod } from 'vega-slimmer/core';
import { isTimeStr } from '../../../../utils/date';
import { LogUtility } from '../../../../utils/log';
import { isArrayEqual } from '../../../../utils/array';
import { FORM_ELEMENT_VALUE_CHANGE } from '../../../../helpers/change-manager/subject/static-subject/static-subject-title';
import ChangeManager from '../../../../helpers/change-manager/change-manager';
/** The `VegaTimePickerValueController` class is responsible for managing the value and behavior of a time picker component. */
export class VegaTimePickerValueController extends VegaSlimmer {
  /**
   * The function emits a change event if the new value is a valid time string or clears the time picker if the new value is not valid or empty.
   *
   * @param {string|string[]} newValue - The `newValue` parameter is a string representing the new value for the time picker.
   * @param {string|string[]} oldValue - The `oldValue` parameter is a string representing the old value for the time picker.
   */
  emitChangeEventOrClearTimePicker(newValue, oldValue) {
    if (this.mode === 'range' &&
      isArrayEqual(newValue, oldValue)) {
      return; // avoid the value changed again by `input blur`, `dropdown item click` in range mode
    }
    if (this.valueGuard(newValue)) {
      this.changeEventEmitter.emit(newValue);
      ChangeManager.notify(FORM_ELEMENT_VALUE_CHANGE, {
        host: this.host,
        detail: newValue,
      });
    }
    else {
      if (this.mode === 'single') {
        this.clearTimePicker();
      }
      else {
        this.clearRangeTimePicker();
      }
    }
  }
  /**
   * The function updates a value if there are selected items.
   */
  updateValueIfSelectedItemsChange() {
    if (this.mode === 'single') {
      if (Object.keys(this.selectedTimeValue).length > 0) {
        this.updateValueBySelectedItems();
      }
    }
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-time-picker-mode-change}
   */
  /* istanbul ignore next */
  /**
   * The function resets the current value if there is a change in mode.
   */
  resetCurrentValueIfModeChange() {
    this.resetValue();
  }
  /**
   * The function checks if the mode is set to 'range' and if the value is not valid, it clears the range time picker.
   */
  checkTheDefaultValueForRangeMode() {
    if (this.mode === 'range' && this.value && !this.valueGuard(this.value)) {
      this.clearRangeTimePicker();
    }
  }
  /*
   * When the filled time format is incorrect, the value needs to be set to empty,
   * the initial value may also be empty, so the input needs to be set to an empty value.
   * The below method is e2e-test covered in
   * @see{module:vega-time-picker-keyboard-control-e2e}
   */
  /* istanbul ignore next */
  /**
   * The function checks the value of an input element after it loses focus and performs certain actions based on the value.
   *
   * @param {NotifyObserverPayload<unknown>} input - input#host is vega-input component
   */
  checkValueAfterInputBlur(input) {
    const vegaInput = input.host;
    if (!this.valueGuard(vegaInput.value)) {
      this.clearTimePicker();
    }
    else if (this.increments > 1 && this.value && vegaInput.value && vegaInput.value !== this.value) {
      vegaInput.value = this.value;
    }
  }
  /**
   * The function sets the value of a variable.
   *
   * @param {string|string[]} value - The parameter "value" is of type string.
   */
  setValue(value) {
    if (this.valueGuard(value)) {
      this.value = value;
    }
  }
  /**
   * The function resets the value property to an empty string or an array depending on the mode property.
   */
  resetValue() {
    this.value = this.mode === 'single' ? '' : ['', ''];
  }
  /**
   * The function updates the value based on the selected time items, taking into account the time
   * format (12-hour or 24-hour).
   */
  updateValueBySelectedItems() {
    const defaultHour = this.timeFormat === '12-hour' ? '12' : '00';
    const hour = this.selectedTimeValue.hour ? this.selectedTimeValue.hour : defaultHour;
    const minute = this.selectedTimeValue.minute ? this.selectedTimeValue.minute : '00';
    const amPm = this.selectedTimeValue.amPm ? this.selectedTimeValue.amPm : 'AM';
    this.timeFormat === '12-hour'
      ? this.setValue(`${hour}:${minute} ${amPm}`)
      : this.setValue(`${hour}:${minute}`);
  }
  /**
   * The function updates a value based on the range type. if change start value, check the end value is a time string, if not check, the start value will block by the value guard
   *
   * @param {string} value - A string value that needs to be updated based on the source code.
   * @param {TimeRangeIndex} rangeIndex - The rangeIndex parameter is of type TimeRangeIndex, which is a string that can have two possible values: 'start' or 'end'.
   */
  updateValueByRangeType(value, rangeIndex) {
    if (rangeIndex === 'start') {
      this.setValue([
        value,
        Array.isArray(this.value) && this.value[1] && isTimeStr(this.value[1], this.timeFormat)
          ? this.value[1]
          : '',
      ]);
    }
    else {
      this.setValue([
        Array.isArray(this.value) && this.value[0] && isTimeStr(this.value[0], this.timeFormat)
          ? this.value[0]
          : '',
        value,
      ]);
    }
  }
  /**
   * This method is used to clear the selected time value in a time picker component.
   */
  clearRangeTimePicker() {
    this.value = ['', ''];
    this.rangeInputRenderer.getStartInputRef().value = '';
    this.rangeInputRenderer.getEndInputRef().value = '';
  }
  /**
   * This method is used to clear the selected time value in a time picker component.
   */
  clearTimePicker() {
    this.value = '';
    this.singleInputRenderer.getInputRef().value = '';
    this.dropdownSelectedItemsController.setSelectedItems({});
  }
  /**
   * The function `valueGuard` checks if the provided value is valid for the specified mode of a time picker component.
   *
   * @param {DatePickerValueType<DatePickerModeType>} value - The `value` parameter is of type `DatePickerValueType<DatePickerModeType>`. It
   * represents the value of the time picker, which can be a single time or a range of times depending on
   * the mode of the time picker.
   * @returns {boolean} a boolean value.
   */
  valueGuard(value) {
    let isValid;
    switch (this.mode) {
      case 'single':
        isValid =
          (value && typeof value === 'string' && isTimeStr(value, this.timeFormat)) || value === '';
        break;
      case 'range':
        isValid =
          Array.isArray(value) &&
            value.length === 2 &&
            value.every((item) => isTimeStr(item, this.timeFormat) || item === '');
        break;
    }
    if (!isValid) {
      LogUtility.warn(`Invalid time picker value ${value} for ${this.mode} mode`);
    }
    return isValid;
  }
}
__decorate([
  MapToComponentField({ writable: true })
], VegaTimePickerValueController.prototype, "value", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "mode", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "timeFormat", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "selectedTimeValue", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "increments", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "changeEventEmitter", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "singleInputRenderer", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "rangeInputRenderer", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "dropdownSelectedItemsController", void 0);
__decorate([
  MapToComponentField()
], VegaTimePickerValueController.prototype, "host", void 0);
__decorate([
  MapToComponentMethod('watchValue')
], VegaTimePickerValueController.prototype, "emitChangeEventOrClearTimePicker", null);
__decorate([
  MapToComponentMethod('watchSelectedTimeValue')
], VegaTimePickerValueController.prototype, "updateValueIfSelectedItemsChange", null);
__decorate([
  MapToComponentMethod('watchMode')
], VegaTimePickerValueController.prototype, "resetCurrentValueIfModeChange", null);
__decorate([
  MapToComponentMethod('componentDidLoad')
], VegaTimePickerValueController.prototype, "checkTheDefaultValueForRangeMode", null);
