import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { DetailsArtitle, InformationArtitle, ResponseFormDetails } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { UnitService } from 'src/app/services/acquisition-management/unit.service';
import { ResponseDataUnit, UnitData } from '../artitle-description-form/artitle-description-form.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { ResourcesService } from 'src/app/services/resources/resources.service';

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

  public displayedColumnsDetails: Array<string>;
  public dataSourceDetails: MatTableDataSource<DetailsArtitle>;

  public arrUnits: Array<UnitData>;
  public isLoading: boolean;

  constructor(
    private _dialogRef: MatDialogRef<any>,
    @Inject(MAT_DIALOG_DATA) public dataDialog: InformationArtitle,
    private _unitService: UnitService,
    public resourcesService: ResourcesService,
    ) {
    this.displayedColumnsDetails = ['CODIGO','MODELO','CANTIDAD','PRECIO','ESTADO','ACCIONES'];
    this.dataSourceDetails = new MatTableDataSource<DetailsArtitle>(this.dataDialog.DETAILS);
    this.arrUnits = [];
    this.isLoading = true;
  }

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

  public openDialog (type:string, elementData?: DetailsArtitle) {
    let obj:ResponseFormDetails = {} as ResponseFormDetails;
    if (type === 'CLOSE') {
      obj = {
        typeForm: type,
        element: this.dataDialog,
      }
    } else if (type === 'FORM_DETAILS') {
      obj = {
        typeForm: type,
        element: this.dataDialog,
        itemElement: elementData
      }
    } else if (type === 'ELIM_DETAILS') {
      obj = {
        typeForm: type,
        element: this.dataDialog,
        itemElement: elementData
      }
    } else if (type === 'REST_DETAILS') {
      obj = {
        typeForm: type,
        element: this.dataDialog,
        itemElement: elementData
      }
    }
    this._dialogRef.close(obj);
  }

  private async getUnits() {
    this.isLoading = true;
    await lastValueFrom(this._unitService.getUnitsActives()).then(
      (responseData: ResponseDataUnit) => {
        let strUnits: string = `{`;
        responseData.response.forEach(element => {
          strUnits += `"${element.ID_UNIDAD}": "${element.UNIDAD}",`
        });
        strUnits = strUnits.substring(0, strUnits.length - 1);
        strUnits += `}`;
        this.arrUnits = JSON.parse(strUnits);
      }, (error:HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }
}

