import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { catchError, map } from 'rxjs';
import { ResponseData } from 'src/app/interfaces/response-data';
import { MESMCCInterface } from '../../../interfaces/mes/mesmcc/mesmcc-interface';
import { IAMService } from '../../iam/iam.service';

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

  constructor(
    private _http: HttpClient,
    private _snackBar: MatSnackBar,
    private _iamService: IAMService
  ) {}

  actualizarContrasena(data: MESMCCInterface) {
    return this._http
      .post<ResponseData>(`${this._url}/MESMCC/cambiar`, data, {
        headers: this.headers,
      })
      .subscribe(
        (res) => {
          if (!res.error) {
            this._iamService.logout();
            this.snackAlert('¡Contraseña Cambiada! Ingrese sus credenciales de acceso de nuevo');
          } 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 snackAlert(mensaje: string) {
    this._snackBar.open(mensaje, 'Cerrar', {
      duration: 4000,
    });
  }
}
