'use strict';
/* jshint latedef: nofunc */
/* NOTE: this is because of the recursive nature of the functions here
    we must be able to call parseObject from inside parseValue,
    if the value is an object
*/


var luxon = require('luxon');

/**
 * Convert string to boolean.
 * @param  {String}  string  - String to convert
 * @return {?}  Returns the results of the conversion.
*/
function parseBoolFromString(string,options) {
  if (string === 'true') {
    return true;
  }
  else if (string === 'false') {
    return false;
  }
  else if( !isNaN(string)  && options?.toNumber) {
      return Number(string);
  } else {
    //Luxon help us to parse a string in a Type `Date`, then, with
    // `isValid` property we can check if `string` is a real Date.
    var isValidDate = luxon.DateTime.fromISO(string).isValid;
    if (isValidDate) { return new Date(string);}
    return string;
  }
  
  
}

/**
 * Recursively test values for conversion.
 * @param  {?}  value  - String to convert
 * @return {?}  Returns the results of the conversion.
*/
function parseValue(value,options) {
  if (typeof value === 'string') {
    return parseBoolFromString(value,options);
  }
  else if (value.constructor === Object) {
    return parseObject(value,options);
  }
  else if (Array.isArray(value)) {
    var array = [];
    value.forEach(function(item, itemKey) {
      array[itemKey] = parseValue(item,options);
    });
    return array;
  }
  else {
    return value;
  }
}

/**
 * Recursively convert object strings to boolean.
 * @param  {Object}  obj  - Object to iterate over
 * @return {Object}  Returns new object (shallow copy).
*/
function parseObject(obj,options={
    toNumber:true
}) {
  var result = {},
      key,
      value;

  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      value = obj[key];
      result[key] = parseValue(value,options);
    }
  }

  return result;
}

module.exports = parseObject;