var InventoryBox = React.createClass({
    getInitialState: function () {
        return {
            data: [],
            data2: []
        };
    },
    handleInventorySubmit: function (inventory) {
    
        $.ajax({
            url: '/inventory',
            dataType: 'json',
            type: 'POST',
            data: inventory,
            success: function(data) {
                this.setState({data:data});
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },
    loadMenuItems: function () {
        $.ajax({
            url: '/getmenuitems',
            dataType: 'json',
            cache: false,
            success: function (data) {
                this.setState({ data2: data});
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },
    componentDidMount: function () {
        this.loadMenuItems();
    },
    render: function () {
        return (
            <div className="InventoryBox">
                <h1>Inventory</h1>
                <Inventoryform2 onInventorySubmit = {this.handleInventorySubmit} data={this.state.data2} />
            </div>
        );
    }
});

var Inventoryform2 = React.createClass({
    getInitialState: function () {
        return {
            menuitemid: "",
            quantityavailable: ""
        };
    },

    handleSubmit: function (e) {

        e.preventDefault();

        var menuitemid = menuitemnum.value;
        var quantityavailable = this.state.quantityavailable.trim();

        if(!quantityavailable) {
            console.log("Field Missing");
            return;
        }

        if(isNaN(quantityavailable)) {
            console.log("Not a number: " + quantityavailable);
            return;
        }

        this.props.onInventorySubmit({
            menuitemid: menuitemid,
            quantityavailable: quantityavailable
        });

    },

    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>Inventory</h2>
                <table>
                    <tbody>
                        <tr>
                            <th>Menu Item</th>
                            <td>
                                <SelectList data={this.props.data} />
                            </td>
                        </tr>
                        <tr>
                            <th>Quantity Available</th>
                            <td>
                                <TextInput
                                    value={this.state.quantityavailable}
                                    uniqueName="quantityavailable"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'quantityavailable')}
                                    errorMessage="Quantity is invalid"
                                    emptyMessage="Quantity is required" />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <input type = "submit" value="Insert Inventory" />
               
            </form>
        );
    }
});

var SelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (menuitem) {
            return (
                <option
                    key={menuitem.dbMenuItemId}
                    value={menuitem.dbMenuItemId}
                >
                    {menuitem.dbMenuItemId} - {menuitem.dbMenuName} 
                </option>
            );
        });
        return (
            <select name="menuitemnum" id="menuitemnum">
                <option key = "0" value = "">Select Menu Item</option>
                {optionNodes}
            </select>
        );
    }
});

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(
    <InventoryBox />,
    document.getElementById('content')
);