import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { map } from 'rxjs';
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 }
    );
  }

  public rechazarSolicitud(solicitud: any) {
    return this.postQuery("/autorizar", solicitud).pipe(map((data: any) => data))
  }

  aprobarSolicitud(solicitud: any) {
    return this.postQuery("/autorizar", solicitud).pipe(map((data: any) => data))
  }

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

  private getQuery(query: string) {
    const URL = `${this._url}${query}`;
    return this.http.get(URL, {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + this.jwt
      })
    });
  }

  private postQuery(query: string, body: any) {
    const URL = `${this._url}${query}`;
    return this.http.post(URL, body, {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + this.jwt
      })
    });
  }

}
