import TVoxSDK from '@telenia/tvox-client-sdk';
import { Component, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatListModule } from '@angular/material/list';
import { TVoxService } from 'src/app/tvox-client-sdk.service';
import { MatTableModule } from '@angular/material/table';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'call-history',
  imports: [
    MatCardModule,
    MatListModule,
    MatButtonModule,
    MatTableModule,
    CommonModule,
  ],
  templateUrl: './call-history.component.html',
  standalone: true,
})
export class CallHistory {
  private client!: TVoxSDK.Client;
  protected tableVisible = signal(false);
  protected callHistoryArray = signal<TVoxSDK.CallHistory.CallHistoryItem[]>(
    []
  );
  readonly displayedColumns: string[] = [
    'contact',
    'type',
    'phone',
    'duration',
  ];

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

  loadCallHistory() {
    this.client.user
      .getCallHistory({ pageNumber: 1, pageSize: 5 }) // metodo per richiedere lo storico delle chiamate
      .then((result) => {
        let value: TVoxSDK.CallHistory.CallHistoryItem[] = [];
        result
          .on('data', (data) => {
            console.log('getCallHistory DATA received: ', data);
            value.push(data);
          })
          .on('error', (error) => {
            console.error('getCallHistory ERROR', error);
          })
          .on('complete', () => {
            console.log('getCallHistory COMPLETE');
            this.callHistoryArray.set(value);
            this.tableVisible.set(true);
          });
      })
      .catch((error) => {
        console.error('getCallHistory ERROR:', error);
      });
  }
}
