var UserBox = React.createClass({
    getInitialState: function () {
        return {
            data: [],
            roledata: []
        };
    },

    loadUsersFromServer: function () {
        var theuserid = "";
        var theusername = "";
        var theuseremail = "";
        var theuserrole = "";

        if (document.getElementById('userid')) {
            theuserid = userid.value;
        }
        if (document.getElementById('username')) {
            theusername = username.value;
        }
        if (document.getElementById('useremail')) {
            theuseremail = useremail.value;
        }
        if (document.getElementById('userrole')) {
            theuserrole = userrole.value;
        }

        $.ajax({
            url: '/getusers',
            data: {
                'userid': theuserid,
                'username': theusername,
                'useremail': theuseremail,
                'userrole': theuserrole,
                'useractive': '1'
            },
            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)
        });
    },

    loadUserRoles: function () {
        $.ajax({
            url: '/getuserroles/',
            dataType: 'json',
            cache: false,
            success: function (data) {
                this.setState({ roledata: data });
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },

    deleteSingleUserFromServer: function (user) {
        $.ajax({
            url: '/deletesingleuser',
            dataType: 'json',
            data: user,
            type: 'POST',
            cache: false,
            success: function (data) {
                this.setState({ data: data });
                this.loadUsersFromServer();

                upuserkey.value = "";
                upuserid.value = "";
                upusername.value = "";
                upuseremail.value = "";
                upuserrole.value = "";
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },

    updateSingleUserFromServer: function (user) {
        $.ajax({
            url: '/updatesingleuser',
            dataType: 'json',
            data: user,
            type: 'POST',
            cache: false,
            success: function (upsingledata) {
                this.setState({ upsingledata: upsingledata });
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
        window.location.reload(true);
    },

    componentDidMount: function () {
        this.loadUserRoles();
        this.loadUsersFromServer();
    },

    render: function () {
        return (
            <div>
                <h1>Update Users</h1>
                <Userform2
                    onUserSubmit={this.loadUsersFromServer}
                    data={this.state.roledata}
                />
                <br />
                <div id="theresults">
                    <div id="theleft">
                        <table>
                            <thead>
                                <tr>
                                    <th>Key</th>
                                    <th>User ID</th>
                                    <th>Username</th>
                                    <th>Email</th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <UserList
                                data={this.state.data}
                                onDeleteSubmit={this.deleteSingleUserFromServer}
                            />
                        </table>
                    </div>
                    <div id="theright">
                        <UserUpdateform
                            onUpdateSubmit={this.updateSingleUserFromServer}
                            data={this.state.roledata}
                        />
                    </div>
                </div>
            </div>
        );
    }
});

var Userform2 = React.createClass({
    getInitialState: function () {
        return {
            userid: "",
            username: "",
            useremail: ""
        };
    },

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

        var theuserid = this.state.userid.trim();
        var theusername = this.state.username.trim();
        var theuseremail = this.state.useremail.trim();
        var theuserrole = document.getElementById('userrole').value;

        this.props.onUserSubmit({
            userid: theuserid,
            username: theusername,
            useremail: theuseremail,
            userrole: theuserrole,
            useractive: '1'
        });
    },

    handleChange: function (event) {
        this.setState({
            [event.target.id]: event.target.value
        });
    },

    render: function () {
        return (
            <div>
                <div id="theform">
                    <form onSubmit={this.handleSubmit}>
                        <h2>Users</h2>
                        <table>
                            <tbody>
                                <tr>
                                    <th>User ID</th>
                                    <td>
                                        <input type="text" name="userid" id="userid" value={this.state.userid} onChange={this.handleChange} />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Username</th>
                                    <td>
                                        <input name="username" id="username" value={this.state.username} onChange={this.handleChange} />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Email</th>
                                    <td>
                                        <input name="useremail" id="useremail" value={this.state.useremail} onChange={this.handleChange} />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Role</th>
                                    <td>
                                        <UserRoleSelectList data={this.props.data} />
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <input type="submit" value="Search User" />
                    </form>
                </div>
                <div>
                    <br />
                    <form onSubmit={this.getInitialState}>
                        <input type="submit" value="Clear Form" />
                    </form>
                </div>
            </div>
        );
    }
});

var UserUpdateform = React.createClass({
    handleUpSubmit: function (e) {
        e.preventDefault();

        var theupuserkey = upuserkey.value;
        var theupuserid = upuserid.value;
        var theupusername = upusername.value;
        var theupuseremail = upuseremail.value;
        var theupuserrole = upuserrole.value;

        this.props.onUpdateSubmit({
            upuserkey: theupuserkey,
            upuserid: theupuserid,
            upusername: theupusername,
            upuseremail: theupuseremail,
            upuserrole: theupuserrole
        });
    },

    render: function () {
        return (
            <div>
                <div id="theform">
                    <form onSubmit={this.handleUpSubmit}>
                        <table>
                            <tbody>
                                <tr>
                                    <th>User ID</th>
                                    <td>
                                        <input type="text" name="upuserid" id="upuserid" readOnly />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Username</th>
                                    <td>
                                        <input name="upusername" id="upusername" />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Email</th>
                                    <td>
                                        <input name="upuseremail" id="upuseremail" />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Role</th>
                                    <td>
                                        <UserRoleUpdateSelectList data={this.props.data} />
                                    </td>
                                </tr>
                            </tbody>
                        </table><br />
                        <input type="hidden" name="upuserkey" id="upuserkey" />
                        <input type="submit" value="Update User" />
                    </form>
                </div>
            </div>
        );
    }
});

var UserList = React.createClass({
    render: function () {
        var userNodes = this.props.data.map(function (user) {
            return (
                <User
                    key={user.dbUserId}
                    userkey={user.dbUserId}
                    userid={user.dbUserId}
                    username={user.dbUsername}
                    useremail={user.dbUserEmail}
                    onDeleteSubmit={this.props.onDeleteSubmit}
                >
                </User>
            );
        }.bind(this));

        return (
            <tbody>
                {userNodes}
            </tbody>
        );
    }
});

var User = React.createClass({
    getInitialState: function () {
        return {
            upuserkey: "",
            singledata: []
        };
    },

    updateRecord: function (e) {
        e.preventDefault();
        var theupuserkey = this.props.userkey;
        this.loadSingleUser(theupuserkey);
    },

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

        var theupuserkey = this.props.userkey;

        if (!confirm("Delete this user record?")) {
            return;
        }

        this.props.onDeleteSubmit({
            deleteid: theupuserkey
        });
    },

    loadSingleUser: function (theupuserkey) {
        $.ajax({
            url: '/getsingleuser',
            data: {
                'upuserid': theupuserkey
            },
            dataType: 'json',
            cache: false,
            success: function (data) {
                this.setState({ singledata: data });
                data.map(function (user) {
                    upuserkey.value = theupuserkey;
                    upuserid.value = user.dbUserId;
                    upusername.value = user.dbUsername;
                    upuseremail.value = user.dbUserEmail;
                    upuserrole.value = user.dbUserRole;
                });
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },

    render: function () {
        return (
            <tr>
                <td>{this.props.userkey}</td>
                <td>{this.props.userid}</td>
                <td>{this.props.username}</td>
                <td>{this.props.useremail}</td>
                <td>
                    <form onSubmit={this.updateRecord}>
                        <input type="submit" value="Update Record" />
                    </form>
                </td>
                <td>
                    <form onSubmit={this.deleteRecord}>
                        <input type="submit" value="Delete Record" />
                    </form>
                </td>
            </tr>
        );
    }
});

var UserRoleSelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (roles) {
            return (
                <option
                    key={roles.dbUserRoleId}
                    value={roles.dbUserRoleId}
                >
                    {roles.dbUserRoleName}
                </option>
            );
        });

        return (
            <select name="userrole" id="userrole">
                <option value=""></option>
                {optionNodes}
            </select>
        );
    }
});

var UserRoleUpdateSelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (roles) {
            return (
                <option
                    key={roles.dbUserRoleId}
                    value={roles.dbUserRoleId}
                >
                    {roles.dbUserRoleName}
                </option>
            );
        });

        return (
            <select name="upuserrole" id="upuserrole">
                <option value=""></option>
                {optionNodes}
            </select>
        );
    }
});

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