import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ResponseData } from 'src/app/interfaces/response-data';
import { map } from 'rxjs';
import { MCOMUNInterface } from '../../../interfaces/mco/mcomun/mcomun-interface';
import { USERInterface } from 'src/app/interfaces/user-interface';

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

  constructor(private _http: HttpClient, private _snackBar: MatSnackBar) {}
  ngOnInit() {
    this.usuario_session = JSON.parse(localStorage.getItem('TIMUSERENC')!);
  }
  consultaUnidades() {
    this.ngOnInit();
    return this._http
      .get(`${this._url}/consultar/${this.formatoRFC(this.usuario_session.RFCEMPRESA)}`, {
        headers: this.headers,
      })
      .pipe(
        map((data: any) => {
          return data;
        }, (error:any) => {
          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');
          }
        })
      );
  }

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

  registrarUnidad(unidad: MCOMUNInterface) {
    return this._http.post<ResponseData>(`${this._url}/insertar`, unidad, { headers: this.headers });
  }

  modificarUnidad(unidad: any) {
    return this._http.post<ResponseData>(`${this._url}/modificar`, unidad, {
      headers: this.headers,
    });
  }

  eliminarUnidad(unidad: any) {
    return this._http.post<ResponseData>(`${this._url}/eliminar`, unidad, {
      headers: this.headers,
    });
  }

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