import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { NotificationDetailsResponse, NotificationsListItem, NotificationAction } from 'src/app/interfaces/notification.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { NotificationsService } from 'src/app/services/notifications.service';
import { CorrectiveOrderDetailsComponent } from '../../corrective-maintenance/operations-management/corrective-order-details/corrective-order-details.component';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { CorrectiveMaintenanceService } from 'src/app/services/corrective-maintenance.service';

@Component({
  selector: 'app-notification-dialog',
  templateUrl: './notification-dialog.component.html',
  styleUrls: ['./notification-dialog.component.css']
})
export class NotificationDialogComponent implements OnInit {
  idNotification: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  notification: NotificationsListItem | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _notificationsService: NotificationsService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _dialogRef: MatDialogRef<NotificationDialogComponent>,
  ) {
    this.idNotification = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.notification = null;
  }

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

  async init(){
    this.idNotification = await this._encService.decrypt(this._data.idNotification);
    this.getNotification();
  }

  async getNotification(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let notification: NotificationDetailsResponse = await lastValueFrom(this._notificationsService.getNotification(
        this._data.idNotification, 
        'S',
        idUser, 
        1
      ));

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

      if(!this.hasError){
        let notificationActionsArr: NotificationAction[] = JSON.parse(notification.response.ACCIONES);
        
        notification.response.ACCIONES_ARR = notificationActionsArr;
        notification.response.ID_ORDEN = await this._encService.decrypt(notification.response.ID_ORDEN);

        this.notification = notification.response;
      }

      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.isLoading = false;
      this.hasError = true;
    }
  }

  executeNotificationAction(func: string, params: string){
    let paramsArr = JSON.parse(params);
    switch(func){
      case "openCorrectiveWorkOrderDetails":
        this.openCorrectiveWorkOrderDetails(paramsArr[0]);
      break;
      case "validateCorrectiveWorkOrder":
        this.validateCorrectiveWorkOrder(paramsArr[0]);
      break;
      case "openModule":
        this._dialogRef.close(`go|${paramsArr[0]}`);
      break;
      default:
        this._resourcesService.openSnackBar('La función seleccionada no existe.');
      break;
    }
  }

  //FUNCIONES POSIBLES PARA LAS NOTIFICACIONES
  openCorrectiveWorkOrderDetails(idOrder: string){
    this._dialog.open(CorrectiveOrderDetailsComponent, {
      width: '480px',
      data: {
        idOrder: idOrder,
      }
    })
  }

  async validateCorrectiveWorkOrder(idOrder: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_order', idOrder);

      await lastValueFrom(this._correctiveMaintenanceService.approveWorkOrder(formData));
      this._resourcesService.openSnackBar('La orden de trabajo se aprobó correctamente.');
      this._dialogRef.close();
    }catch(error: any){
      if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
