import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { Component, OnInit } from '@angular/core';
import { EncService } from 'src/app/services/enc/enc.service';
import { Submodules, SubmodulesResponse } from 'src/app/interfaces/submodules.interface';
import { ModulesService } from 'src/app/services/modules.service';
import { SubmoduleFunctionsResponse } from 'src/app/interfaces/submodule-functions.interface';
import { SubmoduleFunctionsComponent } from '../template/menu-item/submodule-functions/submodule-functions.component';
import { Router } from '@angular/router';

@Component({
  selector: 'app-preventive-maintenance',
  templateUrl: './preventive-maintenance.component.html',
  styleUrls: ['./preventive-maintenance.component.css']
})
export class PreventiveMaintenanceComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  submodules: Submodules[];

  constructor(
    private _encService: EncService,
    private _modulesService: ModulesService,
    private _dialog: MatDialog,
    private _router: Router,
    private _snackBar: MatSnackBar,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.submodules = [];
  }

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

  async getSubmodules(){
    try{
      let moduleEnc = await this._encService.encrypt('S002V01M10GMPR');
      let idEnc = localStorage.getItem('idusuario')!;
      let submodules: SubmodulesResponse = await lastValueFrom(this._modulesService.getSubmodules(
        moduleEnc,
        idEnc, 
        1
      ));

      this.isLoading = false;
      this.hasError = submodules.error;
      this.errorStr = submodules.msg;

      if(!this.hasError){
        this.submodules = submodules.response;
      }
    }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;
    }
  }

  openMenu(submodule: Submodules){
    let dialogRef = this._dialog.open(SubmoduleFunctionsComponent, {
      width: '560px',
      data: {
        module: 'S002V01M10GMPR',
        submodule: submodule.IDSUBMODULO,
      },
    });
    
    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ""){
        let idFunc = res.IDFUNCION.replace("S002V01F", "");
        idFunc = idFunc.substring(2);
        
        let idSub = submodule.IDSUBMODULO.replace("S002V01S", "");
        idSub = idSub.substring(2);

        this._router.navigate([`sam/GMPR/${idSub}/${idFunc}`]);
      }
    });
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500, 
    })
  }
}
