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

@Component({
    selector: 'app-associated-provider',
    templateUrl: './associated-provider.component.html',
    styleUrl: './associated-provider.component.css',
    standalone: false
})
export class AssociatedProviderComponent implements OnInit {
  public dataSource: MatTableDataSource<any>;
  public displayedColumns: string[];

  public isLoading: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataElement: ArtitleResponse,
    public resourcesService: ResourcesService,
    private _providerService: ProviderService,
    private _encService: EncService,
    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.encrypt(this.dataElement.ID_ARTICULO.toString()), NUMERO_LINEA: '1' }
    )).then(
      (responseData: ResponseDataProviderInformation) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getProviderByArtitle();
        }
      }
    );
    this.isLoading = false;
  }

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