var ReservationBox = React.createClass({
    handleReservationSubmit: function (reservation) {

        $.ajax({
            url: '/reservation',
            dataType: 'json',
            type: 'POST',
            data: reservation,
            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="ReservationBox">
                <h1>Reservations</h1>
                <Reservationform2 onReservationSubmit={this.handleReservationSubmit} />
            </div>
        );
    }
});

var Reservationform2 = React.createClass({
    getInitialState: function () {
        return {
            resdate: "",
            restime: "",
            trainingroom: "",
            data: [],
            data2: []
        };
    },
    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)
        });
    },
    loadTrainers: function () {
        $.ajax({
            url: '/gettrainers',
            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.loadCustomers();
        this.loadTrainers();
    },

handleSubmit: function (e) {

    e.preventDefault();

    var thecustomerid = customerid.value;
    var thetraineruserid = traineruserid.value;
    var resdate = this.state.resdate.trim();
    var restime = this.state.restime.trim();
    var trainingroom = this.state.trainingroom.trim();

    if(!thecustomerid || !thetraineruserid || !resdate || !restime || !trainingroom) {
        console.log("Field Missing");
        return;
    }

    this.props.onReservationSubmit({
        customerid: thecustomerid,
        traineruserid: thetraineruserid,
        resdate: resdate,
        restime: restime,
        trainingroom: trainingroom
    });

},

    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>Reservations</h2>
                <table>
                    <tbody>
                        <tr>
                            <th>Customer</th>
                            <td>
                                <CustomerSelectList data={this.state.data} />
                            </td>
                        </tr>
                        <tr>
                            <th>Trainer</th>
                            <td>
                                <TrainerSelectList data={this.state.data2} />
                            </td>
                        </tr>
                        <tr>
                            <th>Date</th>
                            <td>
                                <TextInput
                                    value={this.state.resdate}
                                    uniqueName="resdate"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'resdate')}
                                    errorMessage="Date is invalid"
                                    emptyMessage="Date is required" />
                            </td>
                        </tr>
                        <tr>
                            <th>Time</th>
                            <td>
                                <TextInput
                                    value={this.state.restime}
                                    uniqueName="restime"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'restime')}
                                    errorMessage="Time is invalid"
                                    emptyMessage="Time is required" />
                            </td>
                        </tr>
                        <tr>
                            <th>Training Room</th>
                            <td>
                                <TextInput
                                    value={this.state.trainingroom}
                                    uniqueName="trainingroom"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'trainingroom')}
                                    errorMessage="Training Room is invalid"
                                    emptyMessage="Training Room is required" />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <input type="submit" value="Insert Reservation" />

            </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 TrainerSelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (trainer) {
            return (
                <option
                    key={trainer.dbUserId}
                    value={trainer.dbUserId}
                >
                    {trainer.dbUsername}
                </option>
            );
        });
        return (
            <select name="traineruserid" id="traineruserid">
                <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> {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(
    <ReservationBox />,
    document.getElementById('content')
);