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

@Injectable({
  providedIn: 'root',
})
export class MCOMDFService {
  private _url = 'https://qasirh.ittec.mx/v1/public/api/MCOMDF';
  usuario_session: USERInterface = {} as USERInterface;

  constructor(private http: HttpClient, private _snackBar: MatSnackBar) {}

  ngOnInit() {
    this.usuario_session = JSON.parse(localStorage.getItem('TIMUSERENC')!);
  }

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

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

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

  habilitar(data: any) {
    return this.http
      .post<any>(`${this._url}/habilitar`, data, { headers: this.header })
      .subscribe(
        (res) => {
          if (!res.error) {
            this.snackAlert('Día Feriado Habilitado!');
          } 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) {
    return this.http.post<any>(`${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,
    });
  }
}
