import { BaseSelfControl } from './BaseSelfControl';
import { ValidationChain, ValidationEventArgs } from '../chainOfResponsibility';
import { EnumValidateState } from '../enums';

export class SelfTime extends BaseSelfControl<
  string,
  string,
  string,
  HTMLInputElement
> {
  minValue: string | undefined;
  maxValue: string | undefined;
  private validateNormal = (eventArgs: ValidationEventArgs) => { };
  private validateRequired = (eventArgs: ValidationEventArgs) => {
    if (this.required) {
      if (typeof this.value !== 'number') {
        eventArgs.error = 'اطلاعاتی وارد نشده است';
        eventArgs.state = EnumValidateState.empty;
        eventArgs.cancel = true;
      }
    }
  };
  private validateMinValue = (eventArgs: ValidationEventArgs) => {
    if (this.minValue) {
      if (typeof this.value !== 'number') {
        eventArgs.error = `هیچ مقداری وارد نشده است. حداقل مقدار مجاز:  ${this.minValue}`;
        eventArgs.state = EnumValidateState.minValue;
        eventArgs.cancel = true;
      }
    }
  };
  private validateMaxValue = (eventArgs: ValidationEventArgs) => {
    if (this.maxValue) {
    }
  };

  isValueEmpty = () => {
    return typeof this.#value === 'string' && this.value !== '';
  }
  isValueNotEmpty = () => {
    return !this.isValueEmpty();
  }

  validate = () => {
    var validationChain = new ValidationChain();

    validationChain.validators.add(this.validateNormal);
    validationChain.validators.add(this.validateRequired);
    validationChain.validators.add(this.validateMinValue);
    validationChain.validators.add(this.validateMaxValue);

    this.validation = validationChain.validate();
  };

  public cleaningClassInitializer = () => {
    this.hasChange = false;
    this.defaultValue = undefined;
    this.initializeListener = false;
    this.validation = true;
  };

  public refreshHasChange = () => {
    if (this.showHasChangeFlag) {
      this.hasChange = this.defaultValue !== this.#value;
    }
  };
  public restartDefaultValue = () => {
    this.defaultValue = this.value;
    this.refreshHasChange();
  };

  #value: string;
  public get value() {
    return this.#value;
  }
  public set value(value: any) { }

  public setValue = (value: string) => {
    this.#value = value;
    this.refreshHasChange();
  };

  public deserialize = (value: string) => {
    this.#value = value;
    this.restartDefaultValue();
  };

  constructor(value: string) {
    super();
    this.#value = value;
    this.restartDefaultValue();
  }

  static empty(): SelfTime {
    return new SelfTime('');
  }
  static deserialize(value?: string): SelfTime {
    return new SelfTime(value || '');
  }
}
