import TVoxSDK from '@telenia/tvox-client-sdk';
import { Component, OnInit, signal } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatListModule } from '@angular/material/list';
import { TVoxService } from 'src/app/tvox-client-sdk.service';
import { MatFormField } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'device',
  imports: [
    MatCardModule,
    MatListModule,
    MatFormField,
    MatSelectModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  templateUrl: './device.component.html',
  standalone: true,
})
export class DeviceComponent implements OnInit {
  private client!: TVoxSDK.Client;
  protected availableDeviceList = signal<
    (TVoxSDK.DeviceSip | TVoxSDK.DeviceWebrtc)[]
  >([]);
  protected deviceInUse = signal<string>('');
  protected selectedDevice = new FormControl();

  constructor(private tvoxService: TVoxService) {
    this.client = this.tvoxService.getClient(); // recupero il client istanziato in precedenza all'interno del servizio 'TVoxService'

    this.availableDeviceList.set(this.client.phone.availableDevice); // recupero i dispositivi disponibili
    console.log('availableDeviceList:', this.availableDeviceList());

    const device = this.client.phone.device; // recupero il dispositivo in uso
    console.log('deviceInUse:', device);
    this.deviceInUse.set(
      [device?.label, device?.type, device?.exten].filter(Boolean).join(' - ')
    );

    this.selectedDevice.setValue(device); // seleziono il dispositivo in uso tra quelli disponibili
  }

  ngOnInit(): void {
    this.selectedDevice.valueChanges.subscribe((device) => {
      // useDevice: metodo per cambiare dispositivo in uso
      this.client.phone
        .useDevice(device)
        .then(() => {
          const device = this.client.phone.device;
          // aggiorno il dispositivo in uso
          this.deviceInUse.set(
            [device?.label, device?.type, device?.exten]
              .filter(Boolean)
              .join(' - ')
          );
          console.log('deviceInUse CHANGED', this.deviceInUse());
        })
        .catch((error) => {
          console.error('useDevice ERROR', error);
        });
    });
  }
}
