React = require 'react'
PropTypes = require 'prop-types'
createClass = require 'create-react-class'
ReactDOM = require 'react-dom'
{div} = require 'react-dom-factories'
assign = require 'lodash/assign'

ContextWrapper = createClass
  
  childContextTypes: 
    clearValidationError: PropTypes.func
    addValidationError: PropTypes.func
    getValidationStatus: PropTypes.func
    toggleValidationError: PropTypes.func
    setTabErrorAnchors: PropTypes.func
    openOverlay: PropTypes.func
    closeOverlay: PropTypes.func
  
  getChildContext: ->
    @clearValidationError = sinon.spy()
    @addValidationError = sinon.spy()
    @getValidationStatus = sinon.spy(@getValidationStatusStub)
    @toggleValidationError = sinon.spy()
    @setTabErrorAnchors = sinon.spy()
    @openOverlay = sinon.spy()
    @closeOverlay = sinon.spy()

    {
      @clearValidationError
      @addValidationError
      @getValidationStatus
      @toggleValidationError
      @openOverlay
      @closeOverlay
    }

  componentWillMount: ->
    @ref = @props.childProps?.ref or 'input'
  
  render: -> 
    {factory, childProps, children} = @props
    props = assign {}, childProps, {ref: @ref}

    div {
      key: 'wrapper'
    }, children or factory(props)

  getInput: -> 
    @refs[@ref]

  getInputEl: -> 
    ReactDOM.findDOMNode(@refs[@ref])


  getValidationSpies: ->
    {
      @clearValidationError
      @addValidationError
      @getValidationStatus
      @toggleValidationError
    }

  getValidationStatusStub: ->
    {error, forceShowAllErrors} = @props

    error = if error? then error else null
    forceShowAllErrors = if forceShowAllErrors is yes then yes else no

    {error, forceShowAllErrors}



module.exports = React.createFactory(ContextWrapper)


