/**
 * https://github.com/blakeyc/conversions/blob/master/src/conversions.js
 *
 * */
function convertToMetres(value, unit) {
  switch (unit) {
    case 'km':
      return value * 1000;
    case 'mi':
      return value * (1 / 0.000621371);
    case 'rad': {
      value = value / 0.0174533;
      value = degrees2meters(value, value)[0];
      return value;
    }
    case 'deg':
      return degrees2meters(value, value)[0];
    default:
      return value; // metres
  }
}
function convertToUnit(value, unit) {
  switch (unit) {
    case 'km':
      return value / 1000;
    case 'mi':
      return value * 0.000621371;
    case 'rad':
      return meters2degrees(value, value)[0] * 0.0174533;
    case 'deg':
      return meters2degrees(value, value)[0];
    default:
      return value; // metres
  }
}
function degrees2meters(lon, lat) {
  // credit:  https://gist.github.com/onderaltintas/6649521
  var x = (lon * 20037508.34) / 180;
  var y = Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) / (Math.PI / 180);
  y = (y * 20037508.34) / 180;
  return [x, y];
}
function meters2degrees(x, y) {
  // credit:  https://gist.github.com/onderaltintas/6649521
  var lon = (x * 180) / 20037508.34;
  //thanks magichim @ github for the correction
  var lat = (Math.atan(Math.exp((y * Math.PI) / 20037508.34)) * 360) / (Math.PI - 90);
  return [lon, lat];
}
export function round(value, decimals) {
  const roundedNumber = +parseFloat(value).toFixed(decimals);
  return roundedNumber;
}
export default function ConvertUnit(value, fromUnit, toUnit) {
  const inputValue = +value;
  const from = fromUnit;
  const to = toUnit;
  if (!inputValue)
    throw new Error('Missing value to convert!');
  if (!from || !to)
    throw new Error('Unit/Alias not currently supported!');
  return round(convertToUnit(convertToMetres(inputValue, from), to), 3);
}
