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

@Injectable({
  providedIn: 'root'
})
export class FunctionsService {
  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

  constructor() { }

  orderDate(date: string): string {
    let dateTimeArr = date.split(' ');
    let dateArr = dateTimeArr[0].split('-');
    dateArr = dateArr.reverse();

    let dateStr =dateArr.join('-');
    let timeArr = dateTimeArr[1].split(':');
    let hour = parseInt(timeArr[0]);

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

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

  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];
  }
}
