import { Directive, HostListener, Input, Optional } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  standalone: true,
  selector: '[henselMask]'
})

export class HenselMaskDirective {
  @Input()
  set henselMask(value) {
    this.regExpr = new RegExp(value);
  }

  private _oldvalue: string = '';
  private regExpr: any;
  constructor(@Optional() private control: NgControl) {
  }
  @HostListener('input', ['$event'])
  change($event) {
    const item = $event.target;
    const value = item.value;
    let pos = item.selectionStart;
    const matchvalue = value;
    const noMatch: boolean = (value && !(this.regExpr.test(matchvalue)));
    if (noMatch) {
      item.selectionStart = item.selectionEnd = pos - 1;
      if (item.value.length < this._oldvalue.length && pos === 0) pos = 2;
      if (this.control) this.control.control.setValue(this._oldvalue, { emit: false });

      item.value = this._oldvalue;
      item.selectionStart = item.selectionEnd = pos - 1;
    } else this._oldvalue = value;
  }
}
