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

@Injectable({
  providedIn: 'root',
})
export class MCOMPVService {
  private _url = 'https://qasirh.ittec.mx/v1/public/api/MCOMPV';
  jwt = localStorage.getItem('jwt');
  header = new HttpHeaders().set('Authorization', 'Bearer ' + this.jwt);
  usuario_session: USERInterface = {} as USERInterface;

  constructor(
    private http: HttpClient,
    private _snackBar: MatSnackBar,
    private _iamService: IAMService,
    private _encService: ENCService
  ) {}
  ngOnInit() {
    this.usuario_session = JSON.parse(localStorage.getItem('TIMUSERENC')!);
  }
  obtener() {
    this.ngOnInit();
    return this.http.get<any>(
      `${this._url}/consultar/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}`,
      {
        headers: this.header,
      }
    );
  }

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

  crear(data: any) {
    return this.http
      .post<ResponseData>(`${this._url}/insertar`, data, { headers: this.header });
  }

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

  eliminar(data: string) {
    return this.http.post<ResponseData>(`${this._url}/eliminar`, data, { headers: this.header });
  }

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

  private snackAlert(mensaje: string) {
    this._snackBar.open(mensaje, 'Cerrar', {
      duration: 4000,
    });
  }
}
