import { NON_DIGIT } from "../constants";

const capitalizeFirst = (string) => {
  const split = string.split("-")
  let palabraUnida = ""
  split.forEach((s) => {
    palabraUnida = palabraUnida + s.charAt(0).toUpperCase() + s.slice(1)
  })
  return palabraUnida;
};

const propertyAccesor = (rootObj, accesor = "") => {
  if (!rootObj) return "";
  const properties = accesor.split(".");
  let tmp = rootObj;
  properties.forEach((prop) => (tmp = tmp[prop]));
  return tmp.toString();
};

const serialDateToJSDate = serial => {
  const step = new Date().getTimezoneOffset() <= 0 ? 25567 + 2 : 25567 + 1;
  const utc_days  = Math.floor(serial - step);
  const utc_value = utc_days * 86400;                                        
  const date_info = new Date(utc_value * 1000);
  const fractional_day = serial - Math.floor(serial) + 0.0000001;
  let total_seconds = Math.floor(86400 * fractional_day);
  const seconds = total_seconds % 60;
  total_seconds -= seconds;
  const hours = Math.floor(total_seconds / (60 * 60));
  const minutes = Math.floor(total_seconds / 60) % 60;
  return new Date(date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds);
}

const validateName = (name) => {
  let re = /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/
  return re.test(name);
};

const validateNumber = (number) => {
  const intValue = number.toString().replace(NON_DIGIT, "")
  return !isNaN(intValue);
};

const maskCurrency = (value) => {
  return value?.toLocaleString('es-MX', {minimumFractionDigits: 2})
};

const agregarFaltantes = (data, newData, campo) => {
  let ids = data.map(item => item[campo]);
  let aux = [...data];
  for(let i in newData) {
    let modelo = newData[i];
    if (!modelo){
      continue
    }
    const indice = ids.indexOf(modelo[campo]);
    if(modelo && indice === -1) {
      aux.push(modelo);
    } else {
      aux[indice] = modelo;
    }
  }
  return aux;
};

export { 
  capitalizeFirst,
  propertyAccesor,
  serialDateToJSDate,
  validateName,
  validateNumber,
  maskCurrency,
  agregarFaltantes
};