import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { EncService } from '../enc/enc.service';
import { replace } from '@syncfusion/ej2-angular-spreadsheet';
import { docClassification, environment } from 'src/environments/environment.prod';
import { PermissionsData } from 'src/app/components/acquisition-management/acquisition-management.component';

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

  private arrMonth: Array<string>;
  constructor(
    private _encService: EncService,
    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(httpErrorResponse: HttpErrorResponse) {
    console.log(httpErrorResponse);

    if (httpErrorResponse.ok === false && httpErrorResponse.error.hasOwnProperty('error')) {
      let responseData: ResponseData = httpErrorResponse.error;
      if (responseData.error) {

        if (typeof(responseData.response) === 'object' ) {
          const KEYS: Array<string> = Object.keys(responseData.response);

          if (KEYS.length > 0) {
            const DATAERROR: string = KEYS.toString().replace(',', ', ').trim();
            this.openSnackBar(`Ocurrió un error en ${ KEYS.length > 1 ? 'los campos' : 'el campo'} ${DATAERROR}`);
          } else {
            this.openSnackBar(`${responseData.msg}`);
          }

        } else if (typeof(responseData.response) === 'string'){
          this.openSnackBar(`${responseData.msg} (${responseData.response})`);
        } else {
          this.openSnackBar('Ha ocurrido un error inesperado, favor de comunicarse con el departamento de TI.');
        }
      } else {
        this.openSnackBar(`${responseData.msg}`);
      }
    } else if (httpErrorResponse.ok === false && httpErrorResponse.error.hasOwnProperty('message') && httpErrorResponse.error.hasOwnProperty('exception')) {
      const errorException: ResponseErrorException = httpErrorResponse.error;
      const arrController: Array<string> = errorException.file.split('\\');
      const controller: string = arrController[arrController.length-1];
      this.openSnackBar(`Ocurrió un error inesperado: ${errorException.message} en ${controller}:${errorException.line}`);

    } else if (httpErrorResponse.message.includes("Http failure response for") && httpErrorResponse.statusText === "Unknown Error") {
      this.openSnackBar('No fue posible conectar con el servidor del SAM, favor de contactar al departamento de TI.');

    } else if (httpErrorResponse.status == 408){
      this.openSnackBar('Su conexión no fue apta para conectar con los servidores del SAM.');

    } else {
      this.openSnackBar('Ocurrió un error inesperado, favor de contactar al departamento de TI.');
    }
  }
  public checkErrorsStr(httpErrorResponse: HttpErrorResponse): string {
    console.log(httpErrorResponse);

    if (httpErrorResponse.ok === false && httpErrorResponse.error.hasOwnProperty('error')) {
      let responseData: ResponseData = httpErrorResponse.error;
      if (responseData.error) {

        if (typeof(responseData.response) === 'object' ) {
          const KEYS: Array<string> = Object.keys(responseData.response);

          if (KEYS.length > 0) {
            const DATAERROR: string = KEYS.toString().replace(',', ', ').trim();
            return `Ocurrió un error en ${ KEYS.length > 1 ? 'los campos' : 'el campo'} ${DATAERROR}`;
          } else {
            return `${responseData.msg}`;
          }

        } else if (typeof(responseData.response) === 'string'){
          return `${responseData.msg} (${responseData.response})`;
        } else {
          return 'Ha ocurrido un error inesperado, favor de comunicarse con el departamento de TI.';
        }
      } else {
        return `${responseData.msg}`;
      }
    } else if (httpErrorResponse.ok === false && httpErrorResponse.error.hasOwnProperty('message') && httpErrorResponse.error.hasOwnProperty('exception')) {
      const errorException: ResponseErrorException = httpErrorResponse.error;
      const arrController: Array<string> = errorException.file.split('\\');
      const controller: string = arrController[arrController.length-1];
      return `Ocurrió un error inesperado: ${errorException.message} en ${controller}:${errorException.line}`;

    } else if (httpErrorResponse.message.includes("Http failure response for") && httpErrorResponse.statusText === "Unknown Error") {
      return 'No fue posible conectar con el servidor del SAM, favor de contactar al departamento de TI.';

    } else if (httpErrorResponse.status == 408){
      return 'Su conexión no fue apta para conectar con los servidores del SAM.';

    } else {
      return 'Ocurrió un error inesperado, favor de contactar al departamento de TI.';
    }
  }


  // 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 '';
    }
  }

  public async getShortUser(): Promise<string> {
    let idUser = localStorage.getItem('idusuario');
    let idUserShort = await lastValueFrom(
      this._encService.shortEncrypt(idUser!)
    );

    return idUserShort.response.encrypted;
  }

  public getLineNumber(): string {
    return '1';
  }

  // 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 getDateFormatCalendar(date:Date) {
    let day: string = date.getDate().toString();
    let month: string = this.arrMonth[date.getMonth()];
    let year: string = date.getFullYear().toString();
    return `${year}-${month}-${day}`;
  }

  public resizeText(text:string, numCaracteres:number){    
    let textResize: string = (text.toString()).trim();
    let contact:string = textResize.length > numCaracteres ? '...' : '';
    return textResize.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 formatOnlyDate(date:string):string {
    let arrDate:Array<string> = date.split('-');
    return `${arrDate[2]}-${arrDate[1]}-${arrDate[0]}`;
  }

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

  public getTypeFile(codeFile:string) {
    const arrCatgory: Array<CategoryFile> = docClassification;

    let dataFile = arrCatgory.find((element:CategoryFile) => element.code === codeFile);
    if (dataFile === null || dataFile === undefined) {
      return 'No encontrado';
    }

    return dataFile.category;
  }

  public convertisBase64Old = async ($event: File) => new Promise((resolve) => {
    try {
      let reader = new FileReader();
      reader.readAsDataURL($event);
      reader.onload = () => { resolve({ base: reader.result }); };
      reader.onerror = () => { resolve({ base: null }); };

    } catch (error) {
      return '';
    }
    return resolve;
  });

  public async convertisBase64($event: File) {
    return new Promise((resolve, reject) => {
      var fr = new FileReader();  
      fr.onload = () => {
        resolve(fr.result )
      };
      fr.onerror = reject;
      // fr.readAsText($event.blob);
    });
    
  }

  public moneyFormat(money:number): string {
    let newFormat: string = '';

    const formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    });

    newFormat = formatter.format(money);
    return newFormat;
  }

  // Método para regresar a la pantalla anterior
  public goBack() {
    window.history.back();
  }

  public onResize(): boolean {
    return window.innerWidth <= 1650
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string, dataSource: MatTableDataSource<any>, isLoading: boolean, ) {
    if (!isLoading) {
      let filterValue:string;
      if (type == 'INP') {
        filterValue = (event.target as HTMLInputElement).value;
      }else{
        // this.txtSearch = event;
        filterValue = event;
      }
      dataSource.filter = filterValue.trim().toLowerCase();
      if (dataSource.paginator) {
        dataSource.paginator.firstPage();
      }
    }
    return dataSource;
  }

}

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

export interface ResponseErrorException {
  exception: string;
  file: string;
  line: number;
  message: string;
}

export interface CategoryFile {
  category: string;
  code: string;
}