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

    handleUserSubmit: function (user) {
        $.ajax({
            url: '/user',
            dataType: 'json',
            type: 'POST',
            data: user,
            success: function (data) {
                this.setState({ data: data });
                alert("User inserted successfully");
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },

    render: function () {
        return (
            <div className="UserBox">
                <h1>Users</h1>
                <Userform2 onUserSubmit={this.handleUserSubmit} />
            </div>
        );
    }
});

var Userform2 = React.createClass({
    getInitialState: function () {
        return {
            username: "",
            useremail: "",
            userpw: "",
            userpw2: "",
            userrole: "",
            data: []
        };
    },

    loadUserRoles: function () {
        $.ajax({
            url: '/getuserroles/',
            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.loadUserRoles();
    },

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

        var username = this.state.username.trim();
        var useremail = this.state.useremail.trim();
        var userpw = this.state.userpw.trim();
        var userpw2 = this.state.userpw2.trim();
        var userrole = this.state.userrole.trim();

        if (!this.validateEmail(useremail)) {
            console.log("Bad Email!!!");
            alert("Invalid E-Mail Address");
            return;
        }

        if (userpw != userpw2) {
            console.log("Passwords do not match!!");
            alert("Passwords do not match!!");
            return;
        }

        if (!username || !useremail || !userpw || !userrole) {
            console.log("Field Missing");
            alert("All fields are required");
            return;
        }

        this.props.onUserSubmit({
            username: username,
            password: userpw,
            email: useremail,
            role: userrole
        });

        this.setState({
            username: "",
            useremail: "",
            userpw: "",
            userpw2: "",
            userrole: ""
        });
    },

    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);
    },

    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>Users</h2>
                <table>
                    <tbody>
                        <tr>
                            <th>Username</th>
                            <td>
                                <TextInput
                                    value={this.state.username}
                                    uniqueName="username"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'username')}
                                    errorMessage="Username is invalid"
                                    emptyMessage="Username is required" />
                            </td>
                        </tr>
                        <tr>
                            <th>User Password</th>
                            <td>
                                <TextInput
                                    inputType="password"
                                    value={this.state.userpw}
                                    uniqueName="userpw"
                                    textArea={false}
                                    required={true}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'userpw')}
                                    errorMessage="Invalid Password"
                                    emptyMessage="Password is Required" />
                            </td>
                        </tr>
                        <tr>
                            <th>User Password Confirm</th>
                            <td>
                                <TextInput
                                    inputType="password"
                                    value={this.state.userpw2}
                                    uniqueName="userpw2"
                                    textArea={false}
                                    required={true}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'userpw2')}
                                    errorMessage="Invalid Password"
                                    emptyMessage="Password is Required" />
                            </td>
                        </tr>
                        <tr>
                            <th>User E-Mail</th>
                            <td>
                                <TextInput
                                    value={this.state.useremail}
                                    uniqueName="useremail"
                                    textArea={false}
                                    required={true}
                                    validate={this.validateEmail}
                                    onChange={this.setValue.bind(this, 'useremail')}
                                    errorMessage="Invalid E-Mail Address"
                                    emptyMessage="E-Mail Address is Required" />
                            </td>
                        </tr>
                        <tr>
                            <th>User Role</th>
                            <td>
                                <UserRoleSelectList
                                    data={this.state.data}
                                    selectedValue={this.state.userrole}
                                    onSelectChange={this.setValue.bind(this, 'userrole')}
                                />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <input type="submit" value="Insert User" />
            </form>
        );
    }
});

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"
                value={this.props.selectedValue}
                onChange={this.props.onSelectChange}
            >
                <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(
    <UserBox />,
    document.getElementById('content')
);