const decimalsValidator = (value, param) => {
  if (value == null || value === '') {
    return true
  }

  const decimals = param[0]
  const separator = '.'

  if (Array.isArray(value)) {
    return value.every((val) => this(val, param))
  }

  // if is 0.
  if (Number(decimals) === 0) {
    return /^-?\d*$/.test(value)
  }

  const regexPart = decimals === '*' ? '+' : `{1,${decimals}}`
  const regex = new RegExp(
    `^[-+]?\\d*(\\${separator}\\d${regexPart})?([eE]{1}[-]?\\d+)?$`
  )

  if (!regex.test(value)) {
    return false
  }

  const parsedValue = parseFloat(value)

  // eslint-disable-next-line
  return parsedValue === parsedValue
}


const phoneValidator = (value, param) => {
  if (value == null || value === '') {
    return true
  }

  if (Array.isArray(value)) {
    return value.every((val) => this(val, param))
  }

  if (!/^(\+?1?\s?)(\(?[0-9]{3}\)?(\s?-?\.?)[0-9]{3}(\s?-?\.?)[0-9]{4})|(\+[0-9]{6,15})$/.test(value)) {
    return false
  }

  return true
}

export default {
  decimals: decimalsValidator,
  phone: phoneValidator
}
