import React from 'react';
import ReactDOM from 'react-dom';
import AlertMessages from './AlertMessages';
import Fields from '../../utils/fields';
import InvalidFieldType from './InvalidFieldType';
import { Button, Form, Modal } from 'elemental';

var CreateForm = React.createClass({
	displayName: 'CreateForm',
	propTypes: {
		err: React.PropTypes.object,
		isOpen: React.PropTypes.bool,
		list: React.PropTypes.object,
		onCancel: React.PropTypes.func,
		onCreate: React.PropTypes.func,
		values: React.PropTypes.object,
	},
	getDefaultProps () {
		return {
			err: null,
			values: {},
			isOpen: false,
		};
	},
	getInitialState () {
		var values = Object.assign({}, this.props.values);

		Object.keys(this.props.list.fields).forEach(key => {
			var field = this.props.list.fields[key];

			if (!values[field.path]) {
				values[field.path] = field.defaultValue;
			}
		});
		return {
			values: values,
			alerts: {},
		};
	},
	componentDidMount () {
		if (this.refs.focusTarget) {
			this.refs.focusTarget.focus();
		}
	},
	componentDidUpdate (prevProps) {
		if (this.props.isOpen !== prevProps.isOpen) {
			// focus the focusTarget after the "open modal" CSS animation has started
			setTimeout(() => this.refs.focusTarget && this.refs.focusTarget.focus(), 0);
		}
	},
	handleChange (event) {
		var values = Object.assign({}, this.state.values);
		values[event.path] = event.value;
		this.setState({
			values: values,
		});
	},
	getFieldProps (field) {
		var props = Object.assign({}, field);
		props.value = this.state.values[field.path];
		props.values = this.state.values;
		props.onChange = this.handleChange;
		props.mode = 'create';
		props.key = field.path;
		return props;
	},

	submitForm (event) {
		event.preventDefault();
		const createForm = ReactDOM.findDOMNode(this.refs.createForm);
		const formData = new FormData(createForm);
		this.props.list.createItem(formData, (err, data) => {
			if (data) {
				if (this.props.onCreate) {
					this.props.onCreate(data);
				} else {
					// Clear form
					this.setState({
						values: {},
						alerts: {
							success: {
								success: 'Item created',
							},
						},
					});
				}
			} else {
				this.setState({
					alerts: {
						error: err,
					},
				});
			}
		});
	},
	renderForm () {
		if (!this.props.isOpen) return;

		var form = [];
		var list = this.props.list;
		var nameField = this.props.list.nameField;
		var focusRef;

		if (list.nameIsInitial) {
			var nameFieldProps = this.getFieldProps(nameField);
			nameFieldProps.ref = focusRef = 'focusTarget';
			if (nameField.type === 'text') {
				nameFieldProps.className = 'item-name-field';
				nameFieldProps.placeholder = nameField.label;
				nameFieldProps.label = false;
			}
			form.push(React.createElement(Fields[nameField.type], nameFieldProps));
		}

		Object.keys(list.initialFields).forEach(key => {
			var field = list.fields[list.initialFields[key]];
			if (typeof Fields[field.type] !== 'function') {
				form.push(React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path }));
				return;
			}
			var fieldProps = this.getFieldProps(field);
			if (!focusRef) {
				fieldProps.ref = focusRef = 'focusTarget';
			}
			form.push(React.createElement(Fields[field.type], fieldProps));
		});

		return (
			<Form ref="createForm" type="horizontal" onSubmit={this.submitForm} className="create-form">
				<input type="hidden" name="action" value="create" />
				<input type="hidden" name={Keystone.csrf.key} value={Keystone.csrf.value} />
				<Modal.Header text={'Create a new ' + list.singular} onClose={this.props.onCancel} showCloseButton />
				<Modal.Body>
					<AlertMessages alerts={this.state.alerts} />
					{form}
				</Modal.Body>
				<Modal.Footer>
					<Button type="success" submit>Create</Button>
					<Button type="link-cancel" onClick={this.props.onCancel}>Cancel</Button>
				</Modal.Footer>
			</Form>
		);
	},
	render () {
		return (
			<Modal isOpen={this.props.isOpen} onCancel={this.props.onCancel} backdropClosesModal>
				{this.renderForm()}
			</Modal>
		);
	},
});

module.exports = CreateForm;

@@ -2160,24 +2160,222 @@
 %09%09%09%7D else %7B%0A
+%09%09%09%09// If we get a database error, show the database error message%0A%09%09%09%09// instead of only saying %22Database error%22%0A%09%09%09%09if (err.error === 'database error') %7B%0A%09%09%09%09%09err.error = err.detail.errmsg;%0A%09%09%09%09%7D%0A
 %09%09%09%09this.set

Fix database errors