import { Directive, inject, model, output } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: 'input[uiInputControl]',
  host: { class: 'ui-input-control' },
})
export class InputControlDirective<T> {
  readonly control = inject(NgControl, { optional: true, self: true });

  readonly value = model<T>();
  cleared = output<void>();

  getValue(): T | undefined {
    if (this.control) {
      return this.control.value as T;
    }

    return this.value();
  }

  clear(): void {
    if (this.control) {
      this.control.reset();
    } else {
      this.value.set(undefined);
    }
    this.cleared.emit();
  }
}
