import { BooleanInput } from '@angular/cdk/coercion';
import { Directive, ElementRef, HostBinding, Input, Optional, Self } from '@angular/core';
import { UntypedFormControl, FormControlDirective } from '@angular/forms';

@Directive({ selector: '[ui-input]' })
export class UiInputDirective {
  @HostBinding('class')
  clazz = 'ui-input';

  private _placeholder: string;

  @Input()
  @HostBinding('placeholder')
  get placeholder() {
    return this._placeholder;
  }
  set placeholder(value: string) {
    this._placeholder = value;
  }

  @HostBinding('required')
  get required() {
    if (this._controlDirective) {
      return this._controlDirective.control.validator(new UntypedFormControl())?.required;
    } else {
      return this._elementRef.nativeElement.required;
    }
  }

  @Input()
  @HostBinding('readonly')
  readonly: boolean;

  constructor(
    @Optional() @Self() private readonly _controlDirective: FormControlDirective,
    private _elementRef: ElementRef<UiInputDirective>,
  ) {}
}
