import { Component, inject } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ZXingScannerModule } from '@zxing/ngx-scanner';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { BarcodeFormat } from '@zxing/library';

@Component({
  selector: 'app-qr-scanner',
  templateUrl: './qr-scanner.component.html',
  styleUrls: ['./qr-scanner.component.scss'],
  standalone: true,
  imports: [CommonModule, IonicModule, ZXingScannerModule]
})
export class QrScannerComponent {
  private modalCtrl = inject(ModalController);
  public allowedFormats = [BarcodeFormat.QR_CODE];

  public availableDevices: MediaDeviceInfo[] = [];
  public currentDevice: MediaDeviceInfo | undefined = undefined;

  onCamerasFound(devices: MediaDeviceInfo[]) {
    this.availableDevices = devices;
    if (devices && devices.length > 0) {
      // Cerca la fotocamera posteriore (etichette contenenti 'back', 'rear', 'environment', 'posteriore')
      const backCamera = devices.find(d => {
        const label = d.label.toLowerCase();
        return label.includes('back') || 
               label.includes('rear') || 
               label.includes('environment') || 
               label.includes('posteriore');
      });
      this.currentDevice = backCamera || devices[0];
    }
  }

  toggleCamera() {
    if (this.availableDevices.length <= 1) return;
    const currentIndex = this.availableDevices.findIndex(d => d.deviceId === this.currentDevice?.deviceId);
    const nextIndex = (currentIndex + 1) % this.availableDevices.length;
    this.currentDevice = this.availableDevices[nextIndex];
  }

  get showIpadWarning(): boolean {
    const isIPadDesktop = 
      /Macintosh/.test(navigator.userAgent) && 
      navigator.maxTouchPoints !== undefined && 
      navigator.maxTouchPoints > 1;
    return isIPadDesktop && this.availableDevices.length <= 1;
  }

  onCodeResult(result: string) {
    if (result) {
      this.modalCtrl.dismiss(result);
    }
  }

  cancel() {
    this.modalCtrl.dismiss();
  }
}
