import { EnumValidateState } from '../enums';
import { BasePageData } from './BasePageData';
import { IControlSimulateKey } from './Events';
import { BaseSelfControl } from '../SelfModels/BaseSelfControl';
import { IControlsElementType } from './TabbingControl';

export interface IValidateFields {
  validate?: boolean;
  required?: boolean;
  onlyLastLevel?: boolean;
  minValue?: number | null;
  maxValue?: number | null;
  minLength?: number | null;
  maxLength?: number | null;
  onErrorSimulateKey?: IControlSimulateKey;
}

class ValidatieValuesClass {
  constructor(
    public propertyName: string,
    public controls: IControlsElementType,
  ) { }
}

export type IResultOfValidate = true | [string, EnumValidateState];

export class ValidatingControl {
  public controls: ValidatieValuesClass[] = [];
  constructor(public pageData: BasePageData) { }

  addControl(property: BaseSelfControl<any, any, any, IControlsElementType>) {
    const control = this.controls.find((i) => i.propertyName === property.propertyName);
    if (control) {
      return;
    }

    this.controls.push(new ValidatieValuesClass(property.propertyName!, property.controlRef!.current!));
  }
  removeControl = (
    property: BaseSelfControl<any, any, any, IControlsElementType>
  ) => {
    this.controls = this.controls.filter((i) => i.propertyName !== property.propertyName);
  };
  removeAllControls = () => {
    this.controls = [];
  };

  validateForm = (mainState: any): number => {
    // const props = Array.from(new Set(this.controls.filter(i => !i.disabled).map(i => i.propertyName)));
    if (!this.controls || this.controls.length === 0) {
      return 0;
    }
    let isValid = 0;

    this.pageData.TouchingControl.setAllTouched();
    for (const property of this.controls) {
      const selfControl = mainState[property.propertyName];
      if (selfControl instanceof BaseSelfControl) {
        selfControl.validate();
        if (typeof selfControl.validation !== 'boolean') {
          isValid++;
        }
      }
    }
    this.pageData.Eventing.trigger('form.change');
    return isValid;
  };
}
