import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { CatalogueHistory, CatalogueHistoryResponse } from '../../../../interfaces/catalogue-history.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DOCUMENT } from '@angular/common';
import { EncService } from '../../../../services/enc.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { FunctionsService } from '../../../../services/functions.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-history-viewer',
    templateUrl: './history-viewer.component.html',
    styleUrl: './history-viewer.component.css',
    standalone: false
})
export class HistoryViewerComponent implements OnInit {
  type: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  history: CatalogueHistory[];
  returnData: string;
  
  displayedColumns: string[] = ['id', 'version', 'estado', 'usuareg', 'fechareg', 'acciones'];
  dataSource?: MatTableDataSource<CatalogueHistory>;

  @ViewChild(MatSort) sort?: MatSort;

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: any,
    @Inject(DOCUMENT) public document: Document,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _functionsService: FunctionsService,
  ) { 
    this.type = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.history = [];
    this.returnData = "";
  }

  ngOnInit(): void {
    this.type = this.data['type'];
    this.getCatalogueHistory();
  }

  async getCatalogueHistory(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let history: CatalogueHistoryResponse = await lastValueFrom(this._sysAdminService.getCatalogueHistory(this.type, idUser, 1));

      this.hasError = history.error;
      if(this.hasError){
        this.errorStr = history.msg;
        this.isLoading = false;
      }else{
        this.history = history.response;
        this.dataSource = new MatTableDataSource(this.history);
        this.isLoading = false;
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  orderDate(date: string){
    return this._functionsService.orderDate(date);
  }

  closeWithAction(id: string, action: string){
    let idStr = `${action}${id}`;
    let ref =  this.document.getElementById(idStr);

    ref?.click();
  }
}
