import { Component, signal } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormField } from '@angular/material/form-field';
import { MatListModule } from '@angular/material/list';
import { MatSelectModule } from '@angular/material/select';
import { WidgetService } from 'src/app/widget-configuration.service';

@Component({
  selector: 'app-device',
  imports: [
    MatCardModule,
    MatFormField,
    MatListModule,
    FormsModule,
    ReactiveFormsModule,
    MatSelectModule,
    MatButtonModule,
  ],
  templateUrl: './device.component.html',
  styleUrl: './device.component.scss',
  standalone: true,
})
export class DeviceComponent {
  client: any;

  protected audioInputDeviceList = signal<any[]>([]);
  protected audioOutputDeviceList = signal<any[]>([]);
  protected videoInputDeviceList = signal<any[]>([]);

  protected selectedAudioInputDevice = new FormControl();
  protected selectedAudioOutputDevice = new FormControl();
  protected selectedVideoInputDevice = new FormControl();

  constructor(private widgetService: WidgetService) {
    // recupero la Widget già instanziata in precendenza all'interno del servizio
    this.client = this.widgetService.getClient();
  }

  ngOnInit() {
    this.getLocalMediaAvailable();
  }

  // recupero i dispositivi media disponibili
  getLocalMediaAvailable() {
    this.client
      .getLocalMediaAvailable()
      .then((res: any) => {
        console.log('getLocalMediaAvailable RESULT:', res);
        this.audioInputDeviceList.set(res.audioInput);
        this.audioOutputDeviceList.set(res.audioOutput);
        this.videoInputDeviceList.set(res.videoInput);
      })
      .catch((err: any) => {
        console.error('getLocalMediaAvailable ERROR:', err);
      });
  }

  echoTest() {
    // metodo per eseguire il test dell'eco dei vari dispositivi
    this.client
      .echoTestertSessionNew(
        true,  // audio test attivo
        true,  // video test attivo
        this.selectedAudioInputDevice.value, // microfono selezionato
        this.selectedAudioOutputDevice.value, // altoparlanti selezionati
        this.selectedVideoInputDevice.value, // webcam selezionata
        undefined // timeout personalizzato
      )
      .subscribe({
        next: (session: any) => {
          console.log('echoTestertSessionNew STATO:', session.state);
        },
        error: (err: any) => {
          console.error('echoTestertSessionNew ERROR:', err);
        },
      });
  }
}
