import moment from 'moment';

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

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

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

export function isBetweenDate(value, min, max, type = 'day') {
  if (isDate(min) && isDate(max)) {
    return value.isBetween(min, max, type, '[]');
  }
  return true;
}

export function isBetweenDateTime(value, min, max) {
  return isBetweenDate(value, min, max, null);
}


function isGreater(k, v, type = 'day') {
  if (isDate(v) && isDate(k)) {
    return k.isBefore(v, 'day');
  } else {
    return k > v;
  }
}

function isGreaterDateTime(k, v) {
  return isGreater(k, v, null);
}

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

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

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

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

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, isBetween, isGreater);
}
