"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.parseThenRestateWeight = exports.parseWeightInKg = exports.parseWeight = exports.parsedWeightToString = exports.parseWeightRaw = void 0;

var _metricConversion = require("./metric-conversion");

var _function = require("./function");

const HAS_K_UNIT = /\d+[\s_-]*k/i;
const MAX_KG = 650; // https://en.wikipedia.org/wiki/List_of_the_heaviest_people

const MAX_LBS = parseInt((0, _metricConversion.kgToLbs)(MAX_KG), 10);

const parseWeightRaw = str => {
  if (HAS_K_UNIT.test(str)) {
    return {
      value: parseInt(str, 10),
      unit: 'kg'
    };
  }

  const parsedInt = parseInt(str, 10);

  if (parsedInt) {
    return {
      value: parseInt(str, 10),
      unit: 'lbs'
    };
  }

  return null;
};

exports.parseWeightRaw = parseWeightRaw;

const parsedWeightToString = weightObj => {
  if (!weightObj) {
    return '';
  }

  const {
    unit,
    value
  } = weightObj;
  return "".concat(value).concat(unit);
}; // sanity check max/min values


exports.parsedWeightToString = parsedWeightToString;

const parseWeight = str => {
  const result = parseWeightRaw(str);

  if (!result) {
    return null;
  }

  const {
    value,
    unit
  } = result;

  if (unit === 'kg' && value > MAX_KG) {
    return null;
  }

  if (unit === 'lbs' && value > MAX_LBS) {
    return null;
  }

  return result;
};

exports.parseWeight = parseWeight;

const parseWeightInKg = str => {
  const parsed = parseWeight(str);

  if (!parsed) {
    return null;
  }

  if (parsed.unit === 'kg') {
    return parsed.value;
  }

  return Math.round((0, _metricConversion.lbsToKg)(parsed.value));
};

exports.parseWeightInKg = parseWeightInKg;
const parseThenRestateWeight = (0, _function.singleArgMemoize)(str => parsedWeightToString(parseWeight(str)));
exports.parseThenRestateWeight = parseThenRestateWeight;