import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class ResourcesService {

  private arrMonth: Array<string>;
  constructor(
    private _MatSnackBar: MatSnackBar,
    private _router: Router
  ) {
    this.arrMonth = [];
    this.arrMonth[0] = '01';
    this.arrMonth[1] = '02';
    this.arrMonth[2] = '03';
    this.arrMonth[3] = '04';
    this.arrMonth[4] = '05';
    this.arrMonth[5] = '06';
    this.arrMonth[6] = '07';
    this.arrMonth[7] = '08';
    this.arrMonth[8] = '09';
    this.arrMonth[9] = '10';
    this.arrMonth[10] = '11';
    this.arrMonth[11] = '12';
  }

  public checkErrors(error: HttpErrorResponse) {
    console.log(error);

    if (!error.ok) {
      this.openSnackBar('Ocurrió un error inesperado');
    }
    if (error.error.msg != undefined) {
      this.openSnackBar(error.error.msg);
    }
    if (error.status == 408) {
      this.openSnackBar('Conexion lenta');
    } else if (error.message.includes("Http failure response for") && error.statusText === "Unknown Error") {
      this.openSnackBar('No se pudo conectar al servidor');
    }
  }

  /* public checkRegister(respuesta: ResponseData) {
    if (!respuesta.error) {
      this.openSnackBar('¡Registro exitoso!');
    } else {
      this.openSnackBar(respuesta.msg);
    }
  } */

  // Verifica que el id del usuario se encuentre registrado en el localstorage
  public getUser(): string {
    let idusuario = localStorage.getItem('idusuario')!;
    if (idusuario !== null && idusuario !== undefined) {
      return idusuario;
    } else {
      this.openSnackBarAfter('Ocurrió un error al obtener el usuario, inicie sesión de nuevo.');
      localStorage.clear();
      this._router.navigate(['login']);
      return '';
    }
  }

  // Ejecuta un mensaje
  public openSnackBar(message: string, action: string = "Cerrar", timer: number = 7000) {
    this._MatSnackBar.open(message, action, {
      duration: timer
    });
  }

  //Ejecuta un mensaje después de otro mensaje
  public openSnackBarAfter(message: string, action: string = "Cerrar", timer: number = 7000) {
    setTimeout(() => {
      this._MatSnackBar.open(message, action, {
        duration: timer
      });
    }, 1500)
  }

  public getDateFormat(){
    let dateFormat: Date = new Date();
    return `${dateFormat.getDate()}-${this.arrMonth[dateFormat.getMonth()]}-${dateFormat.getFullYear()}`;
  }

  public resizeText(text:string, numCaracteres:number){
    let contact:string = text.length > numCaracteres ? '...' : '';
    return text.substring(0, numCaracteres) + contact;
  }

  public formatDate(dateRegister:string, dateUpdate:string | null):string {
    let date:string = (dateUpdate === null) ? dateRegister : dateUpdate;
    let arrDateTime:Array<string> = date.split(' ');
    let arrDate:Array<string> = arrDateTime[0].split('-');
    return `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDateTime[1]}`;
  }

  public selectUser(userRegister:string, userUpdate: string | null):string {
    return userUpdate === null ? userRegister : userUpdate;
  }
}

export interface ResponseData {
  error: Boolean,
  msg: string,
  response: any[]
}
