var ManageOrderBox = React.createClass({
    handleOrderSubmit: function (order) {

        $.ajax({
            url: '/order',
            dataType: 'json',
            type: 'POST',
            data: order,
            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="ManageOrderBox">
                <h1>Orders</h1>
                <ManageOrderform2 onOrderSubmit={this.handleOrderSubmit} />
            </div>
        );
    }
});

var ManageOrderform2 = React.createClass({
    getInitialState: function () {
        return {
            data: []
        };
    },
    loadCustomers: function () {
        $.ajax({
            url: '/getcustomers',
            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)
        });
    },
    componentDidMount: function () {
        this.loadCustomers();
    },

    handleSubmit: function (e) {
        e.preventDefault();

        var thecustomerid = customerid.value;
        var theordertype = ordertype.value;
        var theorderstatus = orderstatus.value;

        if (!thecustomerid || !theordertype || !theorderstatus) {
            console.log("Missing some fields");
            return;
        }

        this.props.onOrderSubmit({ 
            customerid: thecustomerid,
            ordertype: theordertype,
            orderstatus: theorderstatus
        });

    },

    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>Orders</h2>
                <table>
                    <tbody>
                        <tr>
                            <th>Customer</th>
                            <td>
                                <CustomerSelectList data={this.state.data} />
                            </td>
                        </tr>
                        <tr>
                            <th>Order Type</th>
                            <td>
                                <OrderTypeSelectList />
                            </td>
                        </tr>
                        <tr>
                            <th>Order Status</th>
                            <td>
                                <OrderStatusSelectList />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <input type="submit" value="Insert Order" />

            </form>
        );
    }
});

var CustomerSelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (customer) {
            return (
                <option
                    key={customer.dbCustomerId}
                    value={customer.dbCustomerId}
                >
                    {customer.dbCustomerName}
                </option>
            );
        });
        return (
            <select name="customerid" id="customerid">
                <option value=""></option>
                {optionNodes}
            </select>
        );
    }
});

var OrderTypeSelectList = React.createClass({
    render: function () {
        return (
            <select name="ordertype" id="ordertype">
                <option value=""></option>
                <option value="Pickup">Pickup</option>
                <option value="Dine-In">Dine-In</option>
            </select>
        );
    }
});

var OrderStatusSelectList = React.createClass({
    render: function () {
        return (
            <select name="orderstatus" id="orderstatus">
                <option value=""></option>
                <option value="Open">Open</option>
                <option value="Closed">Closed</option>
            </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(
    <ManageOrderBox />,
    document.getElementById('content')
);