import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class FunctionsService {
  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
  DAYS = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];

  constructor() { }

  orderDate(date: string): string {
    let dateTimeArr = date.split(' ');
    if(dateTimeArr[0] == undefined || dateTimeArr[0] == 'undefined'){
      return '';
    }else if(dateTimeArr[0].includes('T')){
      let dateJSArr = dateTimeArr[0].split('T');
      dateTimeArr[0] = dateJSArr[0];
    }

    let dateArr = dateTimeArr[0].split('-');
    dateArr = dateArr.reverse();

    let dateStr = dateArr.join('-');
    let timeArr = dateTimeArr[1].split(':');
    let hour = parseInt(timeArr[0]);
    let period = hour < 12 ? 'AM' : 'PM';

    if(hour > 12) hour = hour - 12;
    let hourStr = hour < 10 ? `0${hour}` : `${hour}`;

    timeArr[0] = hourStr;
    let timeStr = timeArr.join(':');
    
    return `${dateStr} ${timeStr} ${period}`;
  }

  notificationDate(date: string): string{
    let dateObj = new Date(date);
    let now = new Date();
    let diff = now.getTime() - dateObj.getTime();

    let diffInSecs = diff / 1000;
    if(diffInSecs < 60){
      return "Hace un momento";
    }

    let diffInMins = diffInSecs / 60;
    if(diffInMins >= 1 && diffInMins < 2){
      return "Hace un minuto";
    }else if(diffInMins < 60){
      let minutes = Math.trunc(diffInMins);
      return `Hace ${minutes} minutos`;
    }

    let diffInHours = diffInMins / 60;
    if(diffInHours >= 1 && diffInHours < 2){
      return "Hace una hora";
    }else if(diffInHours < 24){
      let hours = Math.trunc(diffInHours);
      return `Hace ${hours} horas`;
    }

    let diffInDays = diffInHours / 24;
    if(diffInDays >= 1 && diffInDays < 2){
      return "Ayer";
    }

    let dateTimeArr = date.split(' ');
    let dateArr = dateTimeArr[0].split('-').reverse();
    let dateStr = dateArr.join('/');

    let timeArr = dateTimeArr[1].split(':');
    let hour = parseInt(timeArr[0]);
    let period = hour < 12 ? 'AM' : 'PM';

    hour = hour > 12 ? hour - 12 : hour;
    return `${dateStr} ${hour}:${timeArr[1]} ${period}`;
  }

  buildHumanDate(date: string): string{
    let dateArr = date.split('-').reverse();
    let monthInd = parseInt(dateArr[1]) - 1;
    
    return `${dateArr[0]} de ${this.MONTHS[monthInd]} del ${dateArr[2]}`;
  }

  buildName(no: string, ap: string, am: string | null | undefined): string{
    let name = `${no} ${ap}`;
    if(am != "" && am != undefined && am != null){
      name += ` ${am}`;
    }
    return name;
  }

  formatBytes(bytes: number, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }

  activatorCustomRepeat(value: string): string{
    if(value == ''){
      return '';
    }

    let resObj = JSON.parse(value);
    let repeatEvery = resObj.repeatEvery.split('|');
    let customRepeat = 'Repetir cada ';

    if(repeatEvery[0] != "1"){
      customRepeat += repeatEvery[0];
    }

    switch(repeatEvery[1]){
      case "0": customRepeat += repeatEvery[0] != "1" ? ' días' : ' día'; break;
      case "1": customRepeat += repeatEvery[0] != "1" ? ' semanas' : ' semana'; break;
      case "2": customRepeat += repeatEvery[0] != "1" ? ' meses' : ' mes'; break;
      case "3": customRepeat += repeatEvery[0] != "1" ? ' años' : ' año'; break;
    }

    let days = 0;
    let daysValues = Object.values(resObj.repeatOn);
    let daysStr = '';
    let cont = 0;
    
    daysValues.forEach(val => {
      if(val){
        daysStr += `${this.DAYS[cont]}, `; 
        days++;
      }

      cont++;
    });

    daysStr = daysStr.substring(0, daysStr.length - 2);
    
    if(days > 1){
      customRepeat += ' los días: ';
    }else{
      customRepeat += ' el día: ';
    }

    customRepeat += daysStr;

    let endsAt = resObj.endsAt.split('|');
    if(endsAt[0] == 'O'){
      let dateArr = endsAt[1].split('-').reverse();
      customRepeat += '. Finaliza el ' + dateArr[0] + ' de ' + this.MONTHS[parseInt(dateArr[1])] + ' del ' + dateArr[2] + '.';
    }else if(endsAt[0] == 'A'){
      let after = endsAt[2];
      customRepeat += '. Finaliza después de ' + after + ' repeti';

      if(after == '1'){
        customRepeat += 'ción.';
      }else{
        customRepeat += 'ciones.';
      }
    }

    return `${customRepeat.replace('  ', ' ')}||${value}`;
  }

  activatorRepeat(repeat: string, dateStr: string): string{
    let dateObj = new Date(dateStr);
    if(repeat == 'NR'){
      return 'No se repite';
    }else if(repeat == 'SE'){
      return `Semanalmente los ${this.DAYS[dateObj.getDay()]}`;
    }else if(repeat == 'ME'){
      return `Mensualmente los días ${dateObj.getDate()}`;
    }else if(repeat == 'AN'){
      return `Anualmente el ${dateObj.getDate()} de ${this.MONTHS[dateObj.getMonth()]}`;
    }else if(repeat == 'TD'){
      return `Todos los días a partir del ${this.DAYS[dateObj.getDay()]} ${dateObj.getDate()} de ${this.MONTHS[dateObj.getMonth()]} del ${dateObj.getFullYear()}`
    }else if(repeat == 'PE'){
      return 'Personalizado...';
    }else{
      return 'Desconocido';
    }
  }

  activatorComparision(comparision: string): string{
    if(comparision == 'AC'){
      return 'Acumulado';
    }else if(comparision == 'UR'){
      return 'Último registro';
    }else{
      return 'Desconocido';
    }
  }

  getDateTimeHour(dateTime: string): string{
    let dateTimeArr = dateTime.split(' ');
    let timeArr = dateTimeArr[1].split(':');
    let hour = parseInt(timeArr[0]);
    let period = hour < 12 ? 'AM' : 'PM';
  
    hour = hour > 12 ? hour - 12 : hour;
    let hourStr = hour < 10 ? `0${hour}` : `${hour}`;
    
    return `${hourStr}:${timeArr[1]} ${period}`;
  }
}
