/**
 * @flow
 */

import React from 'react'
import { Action, merge } from '../microcosm'
import serialize from 'form-serialize'

/* istanbul ignore next */
const identity = () => {}

class ActionForm extends React.PureComponent {
  static defaultProps: Object

  send: Sender
  onSubmit: (event: Event) => Action

  constructor(props: Object, context: Object) {
    super(props, context)

    this.send = this.props.send || this.context.send
    this.onSubmit = this.onSubmit.bind(this)
  }

  render() {
    let props = merge(this.props, { ref: 'form', onSubmit: this.onSubmit })

    // Remove invalid props to prevent React warnings
    delete props.action
    delete props.prepare
    delete props.serializer
    delete props.onOpen
    delete props.onDone
    delete props.onUpdate
    delete props.onCancel
    delete props.onError
    delete props.send

    return React.createElement('form', props)
  }

  onSubmit(event: Event) {
    event.preventDefault()
    this.submit(event)
  }

  submit(event: Event) {
    let form = this.refs.form
    let params = this.props.prepare(this.props.serializer(form))
    let action = this.send(this.props.action, params)

    if (action && action instanceof Action) {
      action
        .onOpen(this.props.onOpen)
        .onUpdate(this.props.onUpdate)
        .onCancel(this.props.onCancel)
        .onDone(this.props.onDone)
        .onError(this.props.onError)
    }

    this.props.onSubmit(event, action)
  }
}

ActionForm.contextTypes = {
  send: identity
}

ActionForm.defaultProps = {
  action: null,
  serializer: form => serialize(form, { hash: true, empty: true }),
  prepare: n => n,
  onSubmit: n => n
}

export default ActionForm

@@ -269,16 +269,32 @@
  Sender%0A
+  form: Element%0A
   onSubm
@@ -398,16 +398,37 @@
 ntext)%0A%0A
+    this.form = null%0A
     this
@@ -517,16 +517,61 @@
 d(this)%0A
+    this.assignForm = el =%3E (this.form = el)%0A
   %7D%0A%0A  r
@@ -619,21 +619,42 @@
 s, %7B
- ref: 'form',
+%0A      ref: this.assignForm,%0A     
  onS
@@ -673,16 +673,20 @@
 onSubmit
+%0A   
  %7D)%0A%0A   
@@ -1143,13 +1143,8 @@
 his.
-refs.
 form

Fix strange ref warning