import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MESMAVInterface } from 'src/app/interfaces/mes/mesmav/mesmav-interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { USERInterface } from 'src/app/interfaces/user-interface';
import { ENCService } from '../../enc/enc.service';
import { IAMService } from '../../iam/iam.service';

@Injectable({
  providedIn: 'root',
})
export class MESMAVService {
  private _url = 'https://qasirh.ittec.mx/v1/public/api/MESMAV';

  //usuario: USERInterface = this._iamService.usuario;
  usuario_session: USERInterface = {} as USERInterface;
  jwt: any = '';
  header: HttpHeaders;

  constructor(
    private http: HttpClient,
    private _snackBar: MatSnackBar,
    private _encService: ENCService
  ) {
    this.jwt = localStorage.getItem('jwt');
    this.header = new HttpHeaders().set('Authorization', 'Bearer ' + this.jwt);
  }

  ngOnInit() {
    this.usuario_session = JSON.parse(localStorage.getItem('TIMUSERENC')!);
  }

  consultar() {
    this.ngOnInit();
    return this.http.get<MESMAVInterface>(
      `${this._url}/consultar/${this._encService.desencriptar(
        this.usuario_session.IDUSUARIO
      )}/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}`,
      { headers: this.header }
    );
  }

  rechazarSolicitud(solicitud: any) {
    return this.http.post<ResponseData>(`${this._url}/autorizar`, solicitud, {
      headers: this.header,
    });
  }

  aprobarSolicitud(solicitud: any) {
    return this.http.post<ResponseData>(`${this._url}/autorizar`, solicitud, {
      headers: this.header,
    });
  }

  private formatoRFC(rfc: string){
    let rfc_decoded =  window.atob(rfc);
    let rfc_replace = rfc_decoded.replace("|", "/");
    return rfc_replace;
  } 
}
