import {
  Directive,
  HostBinding,
  HostListener,
  effect,
  inject,
  input,
  signal
} from '@angular/core';
import { KlipyService } from '../application/services/klipy.service';
import type { RoomSignalSourceInput } from '../../server-directory';

@Directive({
  selector: 'img[appChatImageProxyFallback]',
  standalone: true
})
export class ChatImageProxyFallbackDirective {
  readonly sourceUrl = input('', { alias: 'appChatImageProxyFallback' });
  readonly signalSource = input<RoomSignalSourceInput | null>(null);

  private readonly klipy = inject(KlipyService);
  private readonly renderedSource = signal('');
  private hasAppliedProxyFallback = false;

  constructor() {
    effect(() => {
      this.hasAppliedProxyFallback = false;
      this.renderedSource.set(this.klipy.buildRenderableImageUrl(this.sourceUrl()));
    });
  }

  @HostBinding('src')
  get src(): string {
    return this.renderedSource();
  }

  @HostListener('error')
  handleError(): void {
    if (this.hasAppliedProxyFallback) {
      return;
    }

    const proxyUrl = this.klipy.buildImageProxyUrl(this.sourceUrl(), this.signalSource());

    if (!proxyUrl || proxyUrl === this.renderedSource()) {
      return;
    }

    this.hasAppliedProxyFallback = true;
    this.renderedSource.set(proxyUrl);
  }
}
