import {
  Directive,
  TemplateRef,
  ViewContainerRef,
  inject,
  effect,
  input,
} from '@angular/core';
import { ScannerService } from './scanner.service';

/**
 * Structural directive that conditionally renders its content based on scanner ready state.
 *
 * Similar to Angular's *ngIf, but specifically tied to the scanner's readiness.
 * Can be used with an optional else template to show alternative content when the scanner is not ready.
 *
 * @example
 * ```html
 * <div *sharedScannerReady>Content shown when scanner is ready</div>
 *
 * <!-- With else template -->
 * <div *sharedScannerReady="; else notReadyTemplate">Scanner is ready</div>
 * <ng-template #notReadyTemplate>Scanner is not ready yet</ng-template>
 * ```
 */
@Directive({
  selector: '[sharedScannerReady]',
  standalone: true,
})
export class ScannerReadyDirective {
  #scanner = inject(ScannerService);
  #vcRef = inject(ViewContainerRef);
  #tpl = inject(TemplateRef<unknown>);

  /**
   * Optional template to render when scanner is not ready.
   * Similar to *ngIf's else template.
   */
  scannerReadyElse = input<TemplateRef<unknown> | undefined>();

  constructor() {
    effect(() => {
      this.#updateView();
    });
  }

  /**
   * Updates the view based on scanner ready state.
   * Clears the view container and creates the appropriate embedded view.
   */
  #updateView(): void {
    this.#vcRef.clear();
    if (this.#scanner.ready()) {
      this.#vcRef.createEmbeddedView(this.#tpl);
      return;
    }
    const elseTpl = this.scannerReadyElse();
    if (elseTpl) {
      this.#vcRef.createEmbeddedView(elseTpl);
    }
  }
}
