import { Component, Inject, OnInit } from '@angular/core';
import { WorkOrderStatusHistoryListItem, WorkOrderStatusHistoryListResponse } from '../../../../interfaces/corrective-maintenance.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { FunctionsService } from '../../../../services/functions.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-status-timeline',
    templateUrl: './status-timeline.component.html',
    styleUrl: './status-timeline.component.css',
    standalone: false
})
export class StatusTimelineComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  idOrder: string;

  historyArr: WorkOrderStatusHistoryListItem[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _functionsService: FunctionsService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.idOrder = '';

    this.historyArr = [];
  }

  ngOnInit(): void {
    this.idOrder = this._data.idOrder;
    this.getOrderStatusHistory();
  }

  async getOrderStatusHistory(){
    try{
      let idUser =localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(this._data.idOrder);
      let orderStatusHistory: WorkOrderStatusHistoryListResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrderStatusHistory(
        idOrderEnc,
        idUser, 
        1
      ));

      this.hasError = orderStatusHistory.error;
      this.errorStr = orderStatusHistory.msg;

      if(!this.hasError){
        console.log(orderStatusHistory.response);
        let historyArr: WorkOrderStatusHistoryListItem[] = [];
        for(const item of orderStatusHistory.response){
          item.FECHA = this._functionsService.orderDate(item.FECHA);
          historyArr.push(item);
        }

        this.historyArr = historyArr;
      }

      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;
    }
  }
}
