import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { lastValueFrom } from 'rxjs';
import { Submodules, SubmodulesResponse } from 'src/app/interfaces/submodules.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { ModulesService } from 'src/app/services/modules.service';
import { ResourcesService, ResponseErrorException } from 'src/app/services/resources/resources.service';
import { SubmoduleFunctionsComponent } from '../template/menu-item/submodule-functions/submodule-functions.component';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { ResponseData } from 'src/app/interfaces/response-data';
import { PurchasePurpose } from 'src/app/interfaces/acquisition-management/purchase-purpose.interface';

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

  public arrSubmodules: Array<Submodules>;
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  constructor( 
    private _encService: EncService, 
    public resourcesService: ResourcesService, 
    private _modulesService: ModulesService,
    private _dialog: MatDialog,
    private _router: Router,
  ) {
    this.arrSubmodules = [];
    this.isLoading = false;
    this.hasError = false;
    this.errorStr = '';
  }

  async ngOnInit() {
    this.isLoading = true;
    const moduleEnc = await this._encService.encrypt('S002V01M05GEAD');
    const user: string = this.resourcesService.getUser();
    const line: number = parseInt(this.resourcesService.getLineNumber());
    await lastValueFrom(this._modulesService.getSubmodules(moduleEnc, user, line)).then(
      (responseData: SubmodulesResponse) => {
        if (!responseData.error) {
          this.arrSubmodules = responseData.response;          
        } else {
          this.errorStr = `${responseData.msg}`;
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.errorStr = this.resourcesService.checkErrorsStr(httpErrorResponse)
    );
    this.isLoading = false;
  }

  public async openMenu(submodule: Submodules){
    this._dialog.open(SubmoduleFunctionsComponent, {
      width: '560px',
      data: {
        module: 'S002V01M05GEAD',
        submodule: submodule.IDSUBMODULO,
      },
    }).afterClosed().subscribe(async (result) => {
      if (result) {

        
        let idFunc = result.IDFUNCION.replace("S002V01F", "");
        idFunc = idFunc.substring(2);
        
        
        let idSub = submodule.IDSUBMODULO.replace("S002V01S", "");
        idSub = idSub.replace("S002V02S", "");
        idSub = idSub.replace("S002V03S", "");
        idSub = idSub.replace("S002V04S", "");
        idSub = idSub.substring(2);
        
        if (idSub === 'ADQU' && idFunc === 'CGPE') {
          const purchasePurpose:PurchasePurpose = { PROPOSITO: 'NA' };
          const strPurchasePurpose: string = JSON.stringify(purchasePurpose);
          const encPurchasePurpose:string = await this._encService.encrypt(strPurchasePurpose);
          this._router.navigate([`sam/GEAD/${idSub}/${idFunc}/${encPurchasePurpose}`]);

        } else if(idSub === 'ADQU' && idFunc === 'GEDO') {
          const encLineRequest:string = await this._encService.encrypt('0');
          this._router.navigate([`sam/GEAD/${idSub}/${idFunc}/${encLineRequest}`]);

        } else if(idSub === 'PROV' && idFunc === 'SOPR') {          
          const purchasePurpose:PurchasePurpose = { PROPOSITO: 'SOLICITUD' };
          const strPurchasePurpose: string = JSON.stringify(purchasePurpose);
          const encPurchasePurpose:string = await this._encService.encrypt(strPurchasePurpose);
          this._router.navigate([`sam/GEAD/${idSub}/${idFunc}/${encPurchasePurpose}`]);
          
        } else {
          this._router.navigate([`sam/GEAD/${idSub}/${idFunc}`]);
        }        
      }
    });
  }
}

export interface PermissionsData {
  id: string;
  name: string;
  access: number;
  children: Array<PermissionsData>
}