import React, {PropTypes as T} from 'react'

function styles(invalid) {
  return {
    display: 'block',
    width: '100%',
    maxWidth: '100%',
    boxSizing: 'border-box',
    borderColor: '#cccccc',
    backgroundColor: invalid ? 'pink' : 'white',
    fontFamily: 'Menlo, Monaco, Consolas, "Lucida Console", monospace',
  }
}

function stringifyFromUntrustedProp(obj) {
  try {
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    return JSON.stringify({
      message: e.message,
    }, null, 2)
  }
}

export default React.createClass({

  displayName: 'Demo.Controls.InputJson',

  propTypes: {
    value: T.any.isRequired,
    onChange: T.func.isRequired,
  },

  getInitialState() {
    return {
      strValue: stringifyFromUntrustedProp(this.props.value),
      invalid: false,
    }
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      this.setState({
        strValue: stringifyFromUntrustedProp(nextProps.value),
        invalid: false,
      })
    }
  },

  handleChange(event) {
    const nextStrValue = event.target.value
    try {
      this.props.onChange(JSON.parse(nextStrValue))
    } catch (e) {
      this.setState({strValue: nextStrValue, invalid: true})
    }
  },

  render() {
    const {strValue, invalid} = this.state
    return <textarea
      rows={4}
      style={styles(invalid)}
      value={strValue}
      onChange={this.handleChange}
    />
  },

})

@@ -1054,21 +1054,17 @@
   const 
-nextS
+s
 trValue 
@@ -1092,40 +1092,65 @@
     
-try %7B%0A      this.props.onChange(
+let invalid = true%0A    let value%0A    try %7B%0A      value = 
 JSON
@@ -1160,21 +1160,17 @@
 rse(
-nextS
+s
 trValue)
 )%0A  
@@ -1169,87 +1169,172 @@
 lue)
-)%0A    %7D catch (e) %7B%0A      this.setState(%7BstrValue: nextStrValue, invalid: tr
+%0A      invalid = false%0A    %7D catch (e) %7B%7D // eslint-disable-line no-empty%0A    this.setState(%7BstrValue, invalid%7D)%0A    if (!invalid) %7B%0A      this.props.onChange(val
 ue
-%7D
 )%0A  

fix a bug in json control