import {SimpleValidator, TextField} from "@webbpm/base-package";
import {
  IdmValidatorRpcService
} from "../../../generated/ru/micord/ervu/account_applications/component/rpc/IdmValidatorRpcService";

export abstract class AbstractIdmValidator extends SimpleValidator {
  protected abstract ERROR_MESSAGE: string;
  protected abstract checkValueExists(value: string): Promise<boolean>;

  protected textField: TextField;
  protected rpcService: IdmValidatorRpcService;
  protected textInput: HTMLInputElement;

  initialize(): void {
    super.initialize();
    this.textField = this.getScript(TextField);
    this.rpcService = this.getScript(IdmValidatorRpcService);
    this.textInput = this.textField.getEl().nativeElement.querySelector('input');
    this.textInput.addEventListener('blur', this.onBlurHandler.bind(this));
  }

  async isValid(): Promise<boolean> {
    const inputValue: string = this.textInput.value;
    if (!inputValue) return Promise.resolve(false);

    const cleanedValue = this.cleanValue(inputValue);
    if (!this.isPatternValid(cleanedValue)) return Promise.resolve(false);

    return this.checkValueExists(cleanedValue)
        .then(exists => {
          this.pushError(!exists, this.ERROR_MESSAGE);
          return !exists;
        })
        .catch(err => {
          const fieldName = this.textField.getObjectName();
          console.error(`Ошибка проверки ${fieldName}: ${err.message}`);
          return false;
        });
  }

  private async onBlurHandler(event: FocusEvent): Promise<void> {
    await this.isValid();
  }

  protected cleanValue(value: string): string {
    return value;
  }

  protected isPatternValid(value: string): boolean {
    return true;
  }
}