import React from 'react'
import PropTypes from 'prop-types'

class ValidationForm extends React.Component {
  constructor () {
    super()
    this.validationFn = {}
  }

  setValidationFnRoot (key, validationFn) {
    if (validationFn) {
      this.validationFn[key] = validationFn
    } else {
      delete this.validationFn[key]
    }
  }

  getError (showError = false) {
    let errors = []
    Object.keys(this.validationFn).forEach((key) => {
      errors.push(this.validationFn[key](showError))
    })
    errors = errors.filter((e) => { return e.isError })
    return errors
  }

  validateInput (onClick, e) {
    let errors = this.getError(true)
    // if (errors.length > 0) {
    //   let messages = errors.map((e) => { return e.errorMessage })
    //   return
    // }
    if (onClick) {
      onClick(errors, e)
    }
  }

  submitForm (onClick, e) {
    let errors = this.getError(this.props.showErrorOnSubmit)
    if (onClick) {
      onClick(errors, e)
    }
  }

  renderChildren (children, root) {
    children = Array.isArray(children) ? children : [children]
    if (root) {
      this.childrenLength = 0
    }
    return children.map((c, i) => {
      if (!c) {
        return null
      }
      if (Array.isArray(c)) {
        return c.map((c2) => {
          return this.renderChildren(c2)
        })
      }
      let props = { key: i }
      if (c.props && c.props['data-type'] === 'validate') {
        props.onClick = this.validateInput.bind(this, c.props.onClick)
      } else if (c.props && c.props['data-type'] === 'submit') {
        props.onClick = this.submitForm.bind(this, c.props.onClick)
      }
      if (c.type && c.type.prototype && c.type.prototype.isValidationField && c.type.prototype.isValidationField()) {
        return React.cloneElement(c, {
          ...props,
          setValidationFn: this.setValidationFnRoot.bind(this, 'validation' + (this.childrenLength++))
        })
      }
      if (c.props && c.props.children && typeof c.props.children !== 'string') {
        props.children = this.renderChildren(c.props.children)
        return React.cloneElement(c, props)
      }
      if (Object.keys(props).length === 1) return c
      return React.cloneElement(c, props)
    })
  }

  render () {
    let props = {...this.props}
    let children = this.renderChildren(props.children, true)
    return (
      <div>
        {children}
      </div>
    )
  }
}

ValidationForm.propTypes = {
  showErrorOnSubmit: PropTypes.bool
}

export default ValidationForm
