

var Title = '';
var Subject = '';

var EmailCreateTemplate = React.createClass({
    getInitialState: function () {
        return ({
            empty: '',
            data: [],
            template: {id: 'new'},
            updated: false,
            formErrors: [],
            alert: false,
            type: '',
            message: []
        })
    },
    componentDidMount: function () {
        $(EmailTemplateEntity).on('EmailTemplatesHasChanged', function () {
            this.setState({data: EmailTemplateEntity.getEmailTemplates()});
            $(EmailTemplateEntity).off('EmailTemplatesHasChanged');
        }.bind(this));
        EmailTemplateEntity.loadEmailTemplates();
    },
    handleChildChange: function (e) {
        var id = e.target.value;
        if (id == 'new') {
            this.setState({empty: '', template: {id: 'new'}, formErrors: [], alert: false});
        }
        else {
            var newTemp = $.grep(this.state.data, function (temp) {
                return (temp.id == id)
            });
            var temp = newTemp[0];
            this.setState({template: temp, formErrors: [], alert: false});
        }
    },
    handleClick: function (e) {
        var errors = [];
        var options = {};
        options.title = Title;
        options.subject = Subject;
        options.body = getText();

        if (options.title == undefined) {
            errors.push("Title can not be left empty!");
        }
        if (options.subject == undefined) {
            errors.push("Subject can not be left empty!");
        }

        if (errors.length == 0) {
            if (this.state.template.id == 'new') {
                $(EmailTemplateEntity).on('EmailTemplatesHasChanged', function () {
                    this.setState({data: EmailTemplateEntity.getEmailTemplates(), template: {id: 'new'}});
                    this.props.onChangePage("templates");
                    $(EmailTemplateEntity).off('EmailTemplatesHasChanged');
                }.bind(this));
                EmailTemplateEntity.addEmailTemplate(options);
                alert("Template Added");
                EmailTemplateEntity.loadEmailTemplates();

            }
            else
            {
                $(EmailTemplateEntity).on('EmailTemplatesHasChanged', function () {
                    var cur = $.grep(EmailTemplateEntity.getEmailTemplates(), function (template) {
                        return(template.id == this.state.template.id);
                    }.bind(this));
                    cur = cur[0];
                    this.setState({data: EmailTemplateEntity.getEmailTemplates(), template: cur});
                    this.props.onChangePage("templates");
                    $(EmailTemplateEntity).off('EmailTemplatesHasChanged');
                }.bind(this));
                EmailTemplateEntity.updateEmailTemplate(options, this.state.template.id);
                alert("Template Saved");
                EmailTemplateEntity.loadEmailTemplates();
            }
        }
        else {
            this.setState({formErrors: errors});
        }
    },
    handleCloneClick: function (e) {
        var errors = [];
        var options = {};
        options.title = Title;
        options.subject = Subject;
        options.body = getText();

        if (options.title == undefined) {
            errors.push("Title can not be left empty!");
        }
        if (options.subject == undefined) {
            errors.push("Subject can not be left empty!");
        }
        if (this.state.template.id == 'new') {
            errors.push("Cannot Clone a Non-existent Template");
        }

        if (errors.length == 0) {
            $(EmailTemplateEntity).on('EmailTemplatesHasChanged', function () {
                var cur = $.grep(EmailTemplateEntity.getEmailTemplates(), function (template) {
                    return (template.id == this.state.template.id);
                }.bind(this));
                cur = cur[0];
                this.setState({data: EmailTemplateEntity.getEmailTemplates(), template: cur});
                this.props.onChangePage("templates");
                $(EmailTemplateEntity).off('EmailTemplatesHasChanged');
            }.bind(this));
            EmailTemplateEntity.addEmailTemplate(options);
            alert("Template Cloned");
            EmailTemplateEntity.loadEmailTemplates();
        }
        else {
            this.setState({formErrors: errors});
        }
    },
    handleDeleteClick: function (e) {
        var errors = [];
        var options = {};
        options.title = Title;
        options.subject = Subject;
        options.body = getText();

        /*if (options.title == undefined) {
         errors.push("Title can not be left empty!");
         }
         if (options.subject == undefined) {
         errors.push("Subject can not be left empty!");
         }
         if (this.state.template.id == 'new') {
         errors.push("Cannot Clone a Non-existent Template");
         }*/
        var r = confirm("Are you sure you want to delete?");
        if (r == true) {
            $(EmailTemplateEntity).on('FinishedDeleting', function () {
                console.log("HEREEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
                var cur = EmailTemplateEntity.getEmailTemplates();
                cur = cur[0];
                this.setState({data: EmailTemplateEntity.getEmailTemplates(), template: {id: "new"}, alert: true, type: 'success', message: ["The template has been removed from the system."]});
                //this.props.onChangePage("templates");
                $(EmailTemplateEntity).off('FinishedDeleting');
            }.bind(this));
            $(EmailTemplateEntity).on('TemplatesHasDeleted', function () {
                //alert("Template Deleted");
                EmailTemplateEntity.loadDeleteTemplates();
                $(EmailTemplateEntity).off('TemplatesHasDeleted');
            }.bind(this));
            //console.log('before deleting it');
            EmailTemplateEntity.deleteEmailTemplate(this.state.template.id);

        }

    },
    render: function () {
        var curTemplate = this.state.template;
        var shownTemplate = [<SelectedCTemplate template={curTemplate}/>];
        var alert = [<Alert key="message" show={this.state.alert} type={this.state.type} messages={this.state.message}/>];
        return (
            <div data-role="page" id="emailSelectTemplate" className="container">
                {alert}
                <table className="table">
                    <tr>
                        <td style={{textAlign: 'left', verticalAlign: 'bottom'}}>
                            <h1>Template Manager
                            </h1>
                        </td>
                        <td style={{textAlign: 'right', verticalAlign: 'bottom'}}>
                            <button id="send-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleClick}>Save
                            </button>
                            <button id="send-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleCloneClick}>Clone
                            </button>
                            <button id="send-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleDeleteClick}>Delete
                            </button>
                        </td>
                    </tr>
                </table>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Template</td>
                        <td className="td-secondary">
                            <select id="selectedOption" name="selectedOption" ref="templateList" className="borderless"
                                    aria-expanded="true"
                                    onChange={this.handleChildChange} value={this.state.template.id == undefined ? "new" : this.state.template.id}
                                    style={{display: 'block', height: '100%', width:'100%'}}
                                /*onChange={this.handleChildChange(this.props.templates[0].subject)}*/>
                                <option value="new" selected>-- Create New Template --</option>
                                {
                                    $.map(this.state.data, function (template) {
                                        return [<option key={template.id} value={template.id}>{template.title}</option>];
                                    })
                                }
                            </select></td>
                    </tr>

                    </tbody>
                </table>
                {shownTemplate}
            </div>
        );
    }
});

var SelectedCTemplate = React.createClass({
    componentDidMount: function () {
        try {
            CKEDITOR.instances['templateEditor'].destroy(true);
        } catch (e) {
        }
    },
    componentWillReceiveProps: function () {
        try {
            CKEDITOR.instances['templateEditor'].destroy(true);
        } catch (e) {
        }
        var ckEditor = CKEDITOR.replace('templateEditor');
        ckEditor.on('instanceReady', function (e) {
            insertText(this.props.template.body);
        }.bind(this));
    },
    render: function () {
        var template = this.props.template;
        ////console.log(template.subject);
        //insertText(body);
        return (
            <table className="table table-bordered">
                <tbody>
                <TemplateField key="1" id="title" value={template.title} name="Title"/>
                <TemplateField key="2" id="subject" value={template.subject} name="Subject"/>
                <tr>
                    <td className="input-group-addon">Fields To Insert</td>
                    <td className="td-secondary" style={{textAlign:'left'}}>
                        <select className="borderless " id="fieldSelect"
                                style={{display: 'block', width:'100%'}} onChange={(function () {
                                                if ((getSelectIndex('fieldSelect') == 'accept')
                                                || (getSelectIndex('fieldSelect') == 'decline')
                                                || (getSelectIndex('fieldSelect') == 'remove')
                                                || (getSelectIndex('fieldSelect') == 'resetPass')
                                                || (getSelectIndex('fieldSelect') == 'NumberOfStudents')
                                                || (getSelectIndex('fieldSelect') == 'NumberOfProjects')){
                                                    var placeHolder = "[[" + getSelectIndex('fieldSelect') + "]]";
                                                    (insertText(placeHolder));
                                                    $('#fieldSelect').val('');
                                                }
                                                else {
                                                    var rawText = "[[" + getSelectIndex('fieldSelect') + "]]";
                                                    var reducedText = rawText.split('- ')[1];
                                                    var placeHolder = "[[" + reducedText;
                                                    (insertText(placeHolder));
                                                    $('#fieldSelect').val('');
                                                }

                                            })}>
                            <option value="" disabled selected>Select a Field</option>
                            <option value="email">users - email</option>
                            <option value="fname">users - fname</option>
                            <option value="lname">users - lname</option>
                            <option value="title">users - title</option>
                            <option value="affiliation">users - affiliation</option>
                            <option value="projects">users - students</option>
                            <option value="name">terms - name</option>
                            <option value="studentsperjudge">terms - studentsperjudge</option>
                            <option value="start">terms - start</option>
                            <option value="end">terms - end</option>
                            <option value="location">terms - location</option>
                            <option value="mapimage">terms - mapimage</option>
                            <option value="deadline">terms - deadline</option>
                            <option value="mjurl">terms - mjurl</option>
                            <option value="mjdevurl">terms - mjdevurl</option>
                            <option value="projects">projects - projects</option>
                            <option value="questions">questions - questions</option>
                            <option value="accept">accept</option>
                            <option value="decline">decline</option>
                            <option value="remove">remove</option>
                            <option value="resetPass">resetPass</option>
                            <option value="NumberOfStudents">NumberOfStudents</option>
                            <option value="NumberOfProjects">NumberOfProjects</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td colSpan="2">
                        <textarea cols="186" rows="10" id="templateEditor" name="templateEditor"></textarea>
                    </td>
                </tr>
                </tbody>
            </table>
        )
    }
});

var TemplateField = React.createClass({
    getInitialState: function () {
        return ({
            value: '',
            id: '',
            name: ''
        });
    },
    handleChangeField: function (e) {
        ////console.log(Title);
        switch (e.target.id) {
            case "title":
                Title = e.target.value;
                break;
            case "subject":
                Subject = e.target.value;
                break;
            default:
                break;
        }
        this.setState({value: e.target.value});
    },
    componentWillReceiveProps: function (nextProps) {
        this.setState({value: nextProps.value, id: this.props.id, name: this.props.name});
        switch (nextProps.id) {
            case "title":
                Title = nextProps.value;
                break;
            case "subject":
                Subject = nextProps.value;
                break;
            default:
                break;
        }
        ////console.log(nextProps.value);
    },
    render: function () {
        return (
            <tr>
                <td className="input-group-addon" ref="Subject">{this.state.name}</td>
                <td><input id={this.state.id} style={{backgroundColor:'transparent', display: 'block', width: '100%'}}
                           className="borderless" type='text' value={this.state.value}
                           onChange={this.handleChangeField}/>
                </td>
            </tr>
        );
    }
});