import { Component, computed, OnInit } from '@angular/core';
import { CommandService } from '@core/command';
import { UiModalRef } from '../defs/modal-ref';
import { DialogModel } from './dialog.model';
import { parseDialogContentForUrl } from './dialog.helper';

@Component({
  selector: 'ui-dialog-modal',
  templateUrl: './dialog-modal.component.html',
  styleUrls: ['./dialog-modal.component.scss'],
  standalone: false,
})
export class UiDialogModalComponent implements OnInit {
  /**
   * Parsed content with URL extracted for QR code display.
   * Only relevant when showUrlAsQrCode is true.
   */
  readonly parsedContent = computed(() => {
    const data = this.modalRef.data;
    if (!data.showUrlAsQrCode) {
      return null;
    }
    return parseDialogContentForUrl(data.content);
  });

  /**
   * Whether to show the QR code instead of the URL text.
   */
  readonly shouldShowQrCode = computed(() => {
    const parsed = this.parsedContent();
    return parsed !== null && parsed.url !== null;
  });

  constructor(
    public modalRef: UiModalRef<any, DialogModel<any>>,
    private _command: CommandService,
  ) {}

  ngOnInit() {}

  async handleCommand(command: string) {
    if (command === 'CLOSE') {
      this.modalRef.close();
      return;
    }

    if (this.modalRef.data.handleCommand ?? true) {
      await this._command.handleCommand(command, this.modalRef.data.context);
    }

    this.modalRef.close(command);
  }
}
