import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { ArtitleResponse } from 'src/app/interfaces/acquisition-management/acquisition/artitle.interface';
import { ProviderInformation, ResponseDataProviderInformation } from 'src/app/interfaces/acquisition-management/provider/provider.interface';
import { ProviderService } from 'src/app/services/acquisition-management/provider/provider.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-associated-provider',
  templateUrl: './associated-provider.component.html',
  styleUrls: ['./associated-provider.component.css']
})
export class AssociatedProviderComponent implements OnInit {

  public dataSource: MatTableDataSource<any>;
  public displayedColumns: string[];

  public isLoading: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataElement: ArtitleResponse,
    public dialog: MatDialog,
    private _providerService: ProviderService,
    private _encService: EncService,
    public resourcesService: ResourcesService,
    private _dialogRef: MatDialogRef<any>,
  ) {
    this.displayedColumns = ['NO','RAZON_SOCIAL','USUARIO_PROVEEDOR','CORREO','TELEFONO','ACCIONES'];
    this.dataSource = new MatTableDataSource<ProviderInformation>();
    this.isLoading = false;
  }

  ngOnInit(): void {
    this.getProviderByArtitle();
  }

  private async getProviderByArtitle () {
    this.isLoading = true;
    await lastValueFrom(this._providerService.getProviderByArtitle(
      { NUMERO_ARTICULO: await this._encService.encriptar(this.dataElement.ID_ARTICULO), NUMERO_LINEA: '1' }
    )).then(
      (response: ResponseDataProviderInformation) => {
        this.dataSource.data = response.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public openDialog(action: string, dataProvider: ProviderInformation = {} as ProviderInformation) {
    this._dialogRef.close({
      type: action,
      dataElement: {
        provider: dataProvider,
        artitle: this.dataElement
      }
    });
  }

}
