var MenuItemBox = React.createClass({
    getInitialState: function () {
        return { data: [] };
    },
    handleMenuItemSubmit: function (menuitem) {
    
        $.ajax({
            url: '/menuitem',
            dataType: 'json',
            type: 'POST',
            data: menuitem,
            success: function(data) {
                this.setState({data:data});
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },
    render: function () {
        return (
            <div className="MenuItemBox">
                <h1>Menu Items</h1>
                <MenuItemform2 onMenuItemSubmit = {this.handleMenuItemSubmit} />
            </div>
        );
    }
});

var MenuItemform2 = React.createClass({
    getInitialState: function () {
        return {
            menuname: "",
            menudescription: "",
            menuprice: ""
        };
    },

    handleSubmit: function (e) {

        e.preventDefault();

        var menuname = this.state.menuname.trim();
        var menudescription = this.state.menudescription.trim();
        var menuprice = this.state.menuprice.trim();

        if(!menuname || !menudescription || !menuprice) {
            console.log("Field Missing");
            return;
        }

        if(!this.validateDollars(menuprice)) {
            console.log("Did not enter a valid dollar value");
            return;
        }

        this.props.onMenuItemSubmit({
            menuname: menuname,
            menudescription: menudescription,
            menuprice: menuprice
        });

    },

    validateEmail: function (value) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(value);
    },
    validateDollars: function (value) {
        var regex = /^\$?[0-9]+(\.[0-9][0-9])?$/;
        return regex.test(value);
    },
    commonValidate: function () {
        return true;
    },
    setValue: function (field, event) {
        var object = {};
        object[field] = event.target.value;
        this.setState(object);
    },
    render: function () {

        return (
            <form onSubmit={this.handleSubmit}>
                <h2>Menu Items</h2>
                <table>
                    <tbody>
                        <tr>
                            <th>Menu Name</th>
                            <td>
                                <TextInput
                                    value={this.state.menuname}
                                    uniqueName="menuname"
                                    textArea={false}
                                    required={true}
                                    minCharacters={2}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'menuname')}
                                    errorMessage="Menu Name is invalid"
                                    emptyMessage="Menu Name is required" />
                            </td>
                        </tr>
                        <tr>
                            <th>Description</th>
                            <td>
                                <TextInput
                                    value={this.state.menudescription}
                                    uniqueName="menudescription"
                                    textArea={true}
                                    required={true}
                                    minCharacters={3}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'menudescription')}
                                    errorMessage="Description is invalid"
                                    emptyMessage="Description is required" />
                            </td>
                        </tr>
                        <tr>
                            <th>Price</th>
                            <td>
                                <TextInput
                                    value={this.state.menuprice}
                                    uniqueName="menuprice"
                                    textArea={false}
                                    required={true}
                                    validate={this.validateDollars}
                                    onChange={this.setValue.bind(this, 'menuprice')}
                                    errorMessage="Did not enter a valid dollar value"
                                    emptyMessage="Price is required" />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <input type = "submit" value="Insert Menu Item" />
               
            </form>
        );
    }
});

var InputError = React.createClass({
    getInitialState: function () {
        return {
            message: 'Input is invalid'
        };
    },
    render: function () {
        var errorClass = classNames(this.props.className, {
            'error_container': true,
            'visible': this.props.visible,
            'invisible': !this.props.visible
        });

        return (
                <td> {this.props.errorMessage} </td>
        )
    }
});

var TextInput = React.createClass({
    getInitialState: function () {
        return {
            isEmpty: true,
            value: null,
            valid: false,
            errorMessage: "",
            errorVisible: false
        };
    },

    handleChange: function (event) {
        this.validation(event.target.value);

        if (this.props.onChange) {
            this.props.onChange(event);
        }
    },

    validation: function (value, valid) {
        if (typeof valid === 'undefined') {
            valid = true;
        }

        var message = "";
        var errorVisible = false;

        if (!valid) {
            message = this.props.errorMessage;
            valid = false;
            errorVisible = true;
        }
        else if (this.props.required && jQuery.isEmptyObject(value)) {
            message = this.props.emptyMessage;
            valid = false;
            errorVisible = true;
        }
        else if (value.length < this.props.minCharacters) {
            message = this.props.errorMessage;
            valid = false;
            errorVisible = true;
        }

        this.setState({
            value: value,
            isEmpty: jQuery.isEmptyObject(value),
            valid: valid,
            errorMessage: message,
            errorVisible: errorVisible
        });

    },

    handleBlur: function (event) {
        var valid = this.props.validate(event.target.value);
        this.validation(event.target.value, valid);
    },
    render: function () {
        if (this.props.textArea) {
            return (
                <div className={this.props.uniqueName}>
                    <textarea
                        placeholder={this.props.text}
                        className={'input input-' + this.props.uniqueName}
                        onChange={this.handleChange}
                        onBlur={this.handleBlur}
                        value={this.props.value} />

                    <InputError
                        visible={this.state.errorVisible}
                        errorMessage={this.state.errorMessage} />
                </div>
            );
        } else {
            return (
                <div className={this.props.uniqueName}>
                    <input
                        type={this.props.inputType}
                        name={this.props.uniqueName}
                        id={this.props.uniqueName}
                        placeholder={this.props.text}
                        className={'input input-' + this.props.uniqueName}
                        onChange={this.handleChange}
                        onBlur={this.handleBlur}
                        value={this.props.value} />

                    <InputError
                        visible={this.state.errorVisible}
                        errorMessage={this.state.errorMessage} />
                </div>
            );
        }
    }
});

ReactDOM.render(
    <MenuItemBox />,
    document.getElementById('content')
);