import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { map } from 'rxjs';
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 MCOMAPService {
  private _url = 'https://qasirh.ittec.mx/v1/public/api/MCOMAP';
  usuario_session: USERInterface = {} as USERInterface;

  constructor(private http: HttpClient, private _snackBar: MatSnackBar) {
    this.usuario_session = JSON.parse(localStorage.getItem('TIMUSERENC')!);
  }

  jwt = localStorage.getItem('jwt');

  header = new HttpHeaders().set('Authorization', 'Bearer ' + this.jwt);

  obtener(): any {
    return this.http.get<ResponseData>(
      `${this._url}/consultar/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}`,
      { headers: this.header }
    );
  }

  crear(data: any): any {
    return this.http
      .post<ResponseData>(`${this._url}/insertar`, data, {
        headers: this.header,
      })
      .subscribe(
        (res) => {
          if (!res.error) {
            this.snackAlert('¡Registro Exitoso!');
          } else {
            this.snackAlert(res.msg);
          }
        },
        (error) => {
          if (!error.ok) {
            this.snackAlert('Ocurrió un error inesperado');
          }
          if (error.error.msg != undefined) {
            this.snackAlert(error.error.msg);
          }
          if (error.status == 408) {
            this.snackAlert('Conexion lenta');
          }
        }
      );
  }

  modificar(data: any): any {
    return this.http
      .post<ResponseData>(`${this._url}/cambiar`, data, {
        headers: this.header,
      })
      .subscribe(
        (res) => {
          if (!res.error) {
            this.snackAlert('¡Modificación Exitosa!');
          } else {
            this.snackAlert(res.msg);
          }
        },
        (error) => {
          if (!error.ok) {
            this.snackAlert('Ocurrió un error inesperado');
          }
          if (error.error.msg != undefined) {
            this.snackAlert(error.error.msg);
          }
          if (error.status == 408) {
            this.snackAlert('Conexion lenta');
          }
        }
      );
  }

  eliminar(data: any): any {
    return this.http
      .post<ResponseData>(`${this._url}/eliminar`, data, {
        headers: this.header,
      })
      .subscribe(
        (res) => {
          if (!res.error) {
            this.snackAlert('Eliminación Exitoso!');
          } else {
            this.snackAlert(res.msg);
          }
        },
        (error) => {
          if (!error.ok) {
            this.snackAlert('Ocurrió un error inesperado');
          }
          if (error.error.msg != undefined) {
            this.snackAlert(error.error.msg);
          }
          if (error.status == 408) {
            this.snackAlert('Conexion lenta');
          }
        }
      );
  }

  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,
    });
  }
  
}
