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

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

  //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<MESMREInterface>(
      `${this._url}/consultar/${this._encService.desencriptar(
        this.usuario_session.IDUSUARIO
      )}/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}}`,
      { headers: this.header }
    );
  }

  consultarUsuario(id: string) {
    return this.http.get<MESMREInterface>(
      `${this._url}/consultar/${id}/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}}`,
      { headers: this.header }
    );
  }

  consultarTodos(): any {
    return this.http.get<ResponseData>(
      `${this._url}/consultar/todos/${this._encService.desencriptar(
        this.usuario_session.PERFIL
      )}/${this._encService.desencriptar(this.usuario_session.IDUSUARIO)}/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}}`,
      { headers: this.header }
    );
  }

  consultarEmpleados(): any {
    return this.http.get<ResponseData>(
      `${
        this._url_empleados
      }/consultar/empleados/${this._encService.desencriptar(
        this.usuario_session.IDUSUARIO
      )}/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}}`,
      { headers: this.header }
    );
  }

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