import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';

@Directive({
  selector: '[appMaxLength]',
  standalone: true,
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: MaxLengthValidatorDirective,
      multi: true,
    },
  ],
})
export class MaxLengthValidatorDirective implements Validator {
  @Input('appMaxLength') maxLengthValue!: any;
  @Input('LengthTextFieldStatus') LengthTextFieldStatus!: any;

  validate(control: AbstractControl): { [key: string]: any } | null {
    if(this.LengthTextFieldStatus != "on" || (this.maxLengthValue == null || this.maxLengthValue == "" || this.maxLengthValue == 0)){
      return null;
    }
    const maxLength = this.maxLengthValue;
    const value = this.getTextContent(control.value.trim());
    if (value == "<p><br></p>" || value?.length == 0) {
      return {minLength : 1};
    }
    if (value && value.length > maxLength) {
      return {
        maxLength: {
          actualLength: value.length,
          maxLength: maxLength,
        },
      };
    }
    return null
  }

  getTextContent(html: string): string {
    const div = document.createElement('div');
    div.innerHTML = html;
    return div.textContent || div.innerText || '';
  }
}
