export function isDate(value) {
  if (value) {
    if (Array.isArray(value)){
      return value.every(v => v && v.isValid());
    }
    return value.isValid();
  }
}

export function isBetweenMinAndMax(value, min, max) {
  if (isNumber(min) && isNumber(max)) {
    return (value >= min) && (value <= max);
  }
  return true;
}

export function isNumber(value) {
  if (Array.isArray(value)) {
    return value.every(v => (v !=='') && (!isNaN(v)));
  }
  return !isNaN(value);
}

export function validate(value, min, max, errorFormat) {
  if (Array.isArray(value)) {
    if (value[0] > value[1]) {
      return ({ value, error: `Value ${errorFormat(value[0])} should be less equal than ${errorFormat(value[1])}`});
    }

    if (!isBetweenMinAndMax(value[0], min, max)) {
      return ({
        value: value[0],
        error: `Value should be between ${errorFormat(min)} and ${errorFormat(max)}`,
      });
    }

    if (!isBetweenMinAndMax(value[1], min, max)) {
      return ({ value: value[1], error: `Value should be between ${errorFormat(min)} and ${errorFormat(max)}`});
    }
  } else {
    if (!isBetweenMinAndMax(value, min, max)) {
      return ({ value, error: `Value should be between ${errorFormat(min)} and ${errorFormat(max)}`});
    }
  }

}

export function dateHasErrors(value, min, max) {
  const errorFormat = v => v.format('MM/DD/YYYY');
  if (!value || !isDate(value)) {
    return ({ value, error: 'Please select a valid date.' });
  }
  return validate(value, min, max, errorFormat);
}

export function numberHasErrors(value, min, max) {
  const errorFormat = v => v;
  if (!value || !isNumber(value)) {
    return ({ value, error: 'Please enter a valid number.' });
  }
  if (Array.isArray(value)) {
    if (value.length === 2) {
      value = value.map(v => +v);
    } else if (value.length === 1) {
      value = +value[0];
    }
  } else {
    value = +value;
  }
  return validate(value, +min, +max, errorFormat);
}

export function isValidNumber(value, min, max) {
  return validate(value, min, max, isNumber);
}