import TVoxSDK, { ProfileAgent } 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 { MatSelectModule } from '@angular/material/select';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { error } from 'node:console';

@Component({
  selector: 'profile',
  imports: [
    MatCardModule,
    MatListModule,
    MatSelectModule,
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    CommonModule,
    MatButtonModule,
  ],
  templateUrl: './profile.component.html',
  standalone: true,
})
export class ProfileComponent implements OnInit {
  private client!: TVoxSDK.Client;
  protected profiles = signal<TVoxSDK.Profile[]>([]);
  protected currentProfile = signal<TVoxSDK.Profile | undefined>(undefined);
  protected currentActivityCode = signal<any>(undefined);
  protected selectedProfile = new FormControl();
  protected selectedStatus = new FormControl();
  protected selectedActivityCode = new FormControl();
  protected agentStatus = signal<string>('');
  protected activityCodeList = signal<any[]>([]);

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

    this.profiles.set(this.client.user.availableProfile); // recupero i profili disponibili per il mio utente
    console.log('availableProfile:', this.profiles());

    this.currentProfile.set(this.client.user.info.profile); // recupero il profilo in uso al momento
    if (this.currentProfile()?.type == 'AG') {
      const status = (this.client.user.info.profile as ProfileAgent).status;
      this.agentStatus.set(status);
      this.selectedStatus.setValue(status);
      this.getActivityCode();
    }
    this.selectedProfile.setValue(this.client.user.info.profile); // seleziono il profilo in uso
    console.log('currentProfile:', this.currentProfile());
  }

  ngOnInit(): void {
    this.selectedProfile.valueChanges.subscribe((profile) => {
      // metodo per impostare un altro profilo come profilo in uso
      this.client.user
        .useProfile(profile)
        .then(() => {
          this.currentProfile.set(this.client.user.info.profile); // aggiorno il profilo in uso
          if (this.currentProfile()?.type == 'AG') {
            this.getActivityCode();
            const status = (this.client.user.info.profile as ProfileAgent)
              .status;
            this.agentStatus.set(status);
            this.selectedStatus.setValue(status);
          }

          console.log('currentProfile CHANGED', this.currentProfile());
        })
        .catch((error) => {
          console.error('useProfile ERROR', error);
        });
    });

    this.selectedStatus.valueChanges.subscribe((value) => {
      const profile = this.currentProfile();
      if (profile instanceof TVoxSDK.Profile && profile.type === 'AG') {
        if (value == 'READY') {
          // setReady : metodo per impostare lo stato del profilo agente a READY
          (profile as ProfileAgent).setReady().then((response) => {
            response ? this.agentStatus.set('READY') : null;
            console.log('changed ProfileAgent status in READY');
          });
        } else {
          // setNotReady : metodo per impostare lo stato del profilo agente a NR
          (profile as ProfileAgent).setNotReady().then((response) => {
            response ? this.agentStatus.set('NR') : null;
            console.log('changed ProfileAgent status in NR');
          });
        }
      }
    });

    this.selectedActivityCode.valueChanges.subscribe((value) => {
      (this.currentProfile() as ProfileAgent)
        .setActivityCode({
          // metodo per impostare il codice attività
          activityCode: value.id,
          activityCodeLevel2: null,
          note: null,
          pin: null,
        })
        .then((res) => {
          console.log('setActivityCode DONE', value);
          this.currentActivityCode.set(value.id);
        })
        .catch((error) => {
          console.error('setActivityCode ERROR', error);
        });
    });
  }

  profileName(profileType: TVoxSDK.Profile | undefined) {
    switch (profileType?.type) {
      case 'UC':
        return 'Utente';
      case 'AG':
        return 'Agente';
      case 'AG_EXTERNAL':
        return 'Agente esterno';
      case 'AG_REMOTE':
        return 'Agente reperibile';
      case 'TQM':
        return 'Posto operatore';
      default:
        return null;
    }
  }

  getActivityCode() {
    (this.currentProfile() as ProfileAgent)
      .getAllActivityCode() // metodo per recuperare la lista degli activity code
      .then((res) => {
        this.activityCodeList.set(res);
        console.log('getAllActivityCode DONE', this.activityCodeList());

        this.currentActivityCode.set(
          (this.currentProfile() as any).detail.activityCode
        );

        console.log('currentActivityCode:', this.currentActivityCode());

        const selectedActivity = this.activityCodeList().find(
          (activity) => activity.id == this.currentActivityCode()
        );

        this.selectedActivityCode.setValue(
          selectedActivity ? selectedActivity : null
        );
      })
      .catch((error) => {
        console.error('getAllActivityCode ERROR', error);
      });
  }
}
