var OrderDetailsBox = React.createClass({
    handleOrderDetailsSubmit: function (orderdetails) {

        $.ajax({
            url: '/orderdetails',
            dataType: 'json',
            type: 'POST',
            data: orderdetails,
            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="OrderDetailsBox">
                <h1>Order Details</h1>
                <OrderDetailsform2 onOrderDetailsSubmit={this.handleOrderDetailsSubmit} />
            </div>
        );
    }
});

var OrderDetailsform2 = React.createClass({
    getInitialState: function () {
        return {
            orderdetailquantity: "",
            data: [],
            data2: []
        };
    },
    loadOrders: function () {
        $.ajax({
            url: '/getorders',
            dataType: 'json',
            cache: false,
            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.loadOrders();
        this.loadMenuItems();
    },

handleSubmit: function (e) {

    e.preventDefault();

    var theorderid = orderid.value;
    var themenuitemid = menuitemid.value;
    var orderdetailquantity = this.state.orderdetailquantity.trim();

    if(!theorderid || !themenuitemid || !orderdetailquantity) {
        console.log("Field Missing");
        return;
    }

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

    this.props.onOrderDetailsSubmit({
        orderid: theorderid,
        menuitemid: themenuitemid,
        orderdetailquantity: orderdetailquantity
    });

},

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

            </form>
        );
    }
});

var OrderSelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (order) {
            return (
                <option
                    key={order.dbOrderId}
                    value={order.dbOrderId}
                >
                    Order #{order.dbOrderId} - Customer #{order.dbCustomerId}
                </option>
            );
        });
        return (
            <select name="orderid" id="orderid">
                <option value=""></option>
                {optionNodes}
            </select>
        );
    }
});

var MenuItemSelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (item) {
            return (
                <option
                    key={item.dbMenuItemId}
                    value={item.dbMenuItemId}
                >
                    {item.dbMenuName}
                </option>
            );
        });
        return (
            <select name="menuitemid" id="menuitemid">
                <option value=""></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 className={errorClass}> {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(
    <OrderDetailsBox />,
    document.getElementById('content')
);