<polymer-element name="jso-rnaseq-diffexpr" attributes="userData selectedOption selectedStudy studies">
    <template>
        <style>
            :host {
                display: block;
                position: relative;
                box-sizing: border-box;
                padding: 15px 40px;

                z-index: 50000;
                margin: 0px auto 0px auto;

                width: 80%;
                min-width: 800px;
                border: 1px solid #c6d0da;
                transition: all 0.2s;
                box-shadow: 2px 6px 15px 8px rgba(0, 0, 0, 0.30);
                background-color: #FFFFFF;

            }

            .title {
                text-align: center;
                font-size: 25px;
                color: #666;
            }

            .icon {
                color: #445D76;
                font-size: 50px;
            }

            .message {
                margin-top: 20px;
            }

            /*jso-file-browser {*/
            /*width: 70%;*/
            /*}*/

        </style>
        <div class="tooltitle">
            <div>
                RNA differential expression
                <a target="_blank" href="https://github.com/babelomics/babelomics/wiki/Tutorial%20Differential%20Expression%20for%20RNA-Seq">
                    <font-awesome icon="question-circle"></font-awesome>
                </a>
            </div>
            <div class="icon">
                <!--<font-awesome icon="magic"></font-awesome>-->
            </div>
        </div>
        <form id="form">
            <div class="formbox">
                <div class="formtitle">Examples</div>
                <div class="formcontent">
                    <div class="button action" style="display:inline-block" on-click="{{loadExample1}}">Differential expression example</div>
                    <div class="button action" on-click="{{handleDownloadFile}}" data-example="expression.txt" style="display:inline-block">
                        <font-awesome icon="download"></font-awesome>
                    </div>
                </div>
            </div>
            <div class="formbox">
                <div class="formtitle">Select your data</div>
                <div class="formcontent">
                    <jso-project-browser-window id="inputFile" studies="{{studies}}" selectedStudy="{{selectedStudy}}" selectionMode="file" on-ok="{{handleFileSelect}}"
                                                bioformat="DATAMATRIX_EXPRESSION"></jso-project-browser-window>
                </div>
            </div>

            <div class="formbox">
                <div class="formtitle">Select the class to analyse</div>
                <div class="formcontent">
                    <!--<jso-class-viewer id="jsoClassViewer" contentFile="{{contentFile}}" loadedMainSelect="{{loadedMainSelect}}"-->
                    <!--loadedChildrenSelect="{{loadedChildrenSelect}}" changedChildrenSelect="{{changedChildrenSelect}}"-->
                    <!--childrenSelectNumber="2"></jso-class-viewer>-->
                    <jso-class-viewer id="jsoClassViewer" contentFile="{{contentFile}}" on-main-select="{{loadedMainSelect}}"
                                      on-children-select="{{loadedChildrenSelect}}" childrenSelectNumber="2"></jso-class-viewer>
                </div>
            </div>

            <!--<div class="formbox">-->
            <!--<div class="formtitle">Select experimental design file</div>-->
            <!--<div class="formcontent">-->
            <!--<jso-project-browser-window id="edFile" studies="{{studies}}" selectedStudy="{{selectedStudy}}" selectionMode="file" on-file-select="{{handleFileSelect}}"-->
            <!--bioformat=""></jso-project-browser-window>-->
            <!--</div>-->
            <!--</div>-->

            <div class="formbox">
                <div class="formtitle">Normalization method</div>
                <div class="formcontent">
                    <div id="methodDiv" vertical layout>
                        <label class="control">
                            <input id="none" name="method" type="radio" value="NONE" checked="checked" on-click="{{radioTestClicked}}"><span>None</span></label>
                        <label class="control">
                            <input id="tmm" name="method" type="radio" value="TMM" checked="checked" on-click="{{radioTestClicked}}"><span>TMM<span></label>
                        <label class="control">
                            <input id="quan" name="method" type="radio" value="QUAN" on-click="{{radioTestClicked}}"><span>QUAN</span></label>
                    </div>
                </div>
            </div>
            <div id="multiple_test_correction_div">
                <div class="formbox">
                    <div class="formtitle">Select multiple-test correction</div>
                    <div class="formcontent" vertical layout>

                        <label class="control">
                            <input id="correction_1" name="correction" class="fc-radioitem" type="radio" value="fdr" checked="checked"><span>Benjamini
                            and Hochberg (BH), FDR </span></label>
                        <label class="control">
                            <input id="correction_2" name="correction" class="fc-radioitem" type="radio" value="by"><span> Benjamini and
                                Yekutieli (BY) </span></label>
                        <label class="control">
                            <input id="correction_3" name="correction" class="fc-radioitem" type="radio" value="hochberg"><span>Hochberg </span></label>
                        <label class="control">
                            <input id="correction_4" name="correction" class="fc-radioitem" type="radio" value="holm"><span>Holm </span></label>
                        <label class="control">
                            <input id="correction_5" name="correction" class="fc-radioitem" type="radio"
                                   value="bonferroni"><span>Bonferroni</span></label>
                    </div>
                </div>
            </div>
            <div id="adjusted_p_value_div">
                <div class="formbox">
                    <div class="formtitle">Select adjusted p-value</div>
                    <div class="formcontent">
                        <label>Adj. p-value (0.0-1.0)</label>
                        <input name="p_value" id="p_value" class="fc-decimal fc-text" type="text" value="{{p_value}}" style="width: 40px">
                    </div>
                </div>
            </div>
            <div class="formbox">
                <div class="formtitle">Job information</div>
                <div class="formcontent">
                    <label>Output folder</label>
                    <jso-project-browser-window id="outdir" studies="{{studies}}" selectedStudy="{{selectedStudy}}"
                                                selectionMode="folder" showBrowser="false"></jso-project-browser-window>
                    <label>Job name</label> <input type="text" id="jobName" style="width:180px;" value="{{jobName}}" required>
                    <label>Description</label>
                    <textarea value="{{description}}" required></textarea>
                </div>
            </div>
            <div class="botbar" horizontal layout center-justified>
                <div class="button action big" on-click="{{handleForm}}">
                    <font-awesome icon="rocket"></font-awesome>
                    &nbsp; Launch job
                </div>
            </div>
        </form>
        <div class="message">{{message}}</div>
    </template>
    <script>
        Polymer({
            created: function () {
                this.jobName = 'JobName';
                this.toolName = "rnaseq-diffexpr";
                this.description = "Job info..."
                this.p_value = 0.05;
            },
            handleDownloadFile: function (e) {
                Utils.downloadExampleFile(this.toolName, e.currentTarget.dataset.example);
            },

            handleForm: function () {
                var me = this;
                this.message = '';
                me.launchJob();
            },
            handleFileSelect: function (e) {
                this.$.jsoClassViewer.loading = true;
                var file = e.detail.file;
                var me = this;
                if (file.type == "FILE")
                    Utils.getFileContent(function (response) {
                        me.contentFile = response;
                    }, file.id);
            },
            loadedMainSelect: function () {
                /** This is mainly for the examples **/
                var me = this;
                var select = this.$.jsoClassViewer.getMainSelect();
//                select.addEventListener("change", function () {
//                    me.manageClass()
//                });
                if (this.$.inputFile.selectedFile !== undefined && this.$.inputFile.selectedFile.id == "example_expression.txt") {
                    select.value = "organ";
                    this.$.jsoClassViewer.selectChange();
                }
            },
            loadedChildrenSelect: function (oldV, newV) {
                var childrenSelect = this.$.jsoClassViewer.getChildrenSelect();
                /** This is mainly for the examples **/
                if (this.$.inputFile.selectedFile.id == "example_expression.txt") {
                    childrenSelect[0].value = "K";
                    childrenSelect[1].value = "L";
                }
            },
//            manageClass: function () {
//                this.loadedChildrenSelect = false;
//                var select = this.$.jsoClassViewer.getMainSelect();
//                if (select.value == "none") {
//                    this.$.one_rg_1.disabled = true;
//                    this.$.two_rg_1.disabled = true;
//                    this.$.two_rg_2.disabled = true;
//                    this.$.two_rg_3.disabled = true;
//                    this.$.multi_rg_1.disabled = true;
//                    this.$.multi_rg_2.disabled = true;
//                }
//            },
            getClassValues: function () {
                var childrenSelect = this.$.jsoClassViewer.getChildrenSelect();
                var classValues = new Array();
                for (var i = 0; i < childrenSelect.length; i++) {
                    var children = childrenSelect[i];
                    if (children.value != "none") {
                        if (classValues.indexOf(children.value) >= 0) {
                            return "";
                        }
                        classValues.push(children.value)
                    }
                }
                return classValues.join(",");
            },
            launchJob: function () {
                var me = this;
                if (!Utils.basicValidationForm(this)) {
                    return;
                }

                this.class_name = this.$.jsoClassViewer.getMainSelect().value;
                if (this.class_name == "none") {
                    alert("Sorry: Please select a class name.");
                    return;
                }
                this.class_values = this.getClassValues();
                if (this.class_values == "" || this.class_values.split(",").length != 2) {
                    alert("Sorry: There is a problem in the selection of the attributes. Either they are the same or there are some attributes missing");
                    return;
                }
                var query = {
                    sid: Cookies("bioinfo_sid"),
                    studyId: this.selectedStudy.id,
                    toolId: this.toolName,
                    outdir: this.$.outdir.selectedFile.id,
                    name: this.jobName,
                    description: this.description,
                    "datafile": this.$.inputFile.selectedFile.id,
//                    "edfile": this.$.edFile.selectedFile.id,
                    description: this.description,
                    pvmet: this.$.multiple_test_correction_div.querySelector('input[name="correction"]:checked').value,
                    "pval": this.p_value,
                    classname: this.class_name,
                    classvalues: this.class_values
                };
                var method = this.$.methodDiv.querySelector('input[name="method"]:checked').value;
                if (method != "NONE")
                    query["norm"] = method;
                OpencgaManager.jobs.create({
                    query: query,
                    request: {
                        //method: 'POST',
                        success: function (response) {
                            if (response.response[0].errorMsg === '' || response.response[0].errorMsg == null) {
                                var userId = response.response[0].result[0].id;
                                me.message = userId + ' created';
                                me.selectedOption = "jobLaunched"
                            } else {
                                me.message = response.response[0].errorMsg;
                            }
                        },
                        error: function () {
                            me.message = 'Server error, try again later.';
                        }
                    }
                })
            },
            loadExample1: function (e) {
                this.$.jsoClassViewer.loading = true;

                var me = this;
                this.jobName = "RNA differential expression";
                this.description = "Just a differential expression example.";
                this.$.inputFile.selectedFile = {id: "example_expression.txt", path: "expression.txt", type: "FILE"};
//                this.$.edFile.selectedFile = {id: "example_lalm_rnaseq_ed.txt", path: "lalm_rnaseq_ed.txt", type: "FILE"};
                this.$.none.checked = true;
                var exampleFolder = "rna_diffexp";

                Utils.loadExampleFile(function (response) {
                    me.contentFile = response;
                }, this.toolName, this.$.inputFile.selectedFile.path)

                this.createExampleFolder(exampleFolder);


            },
            createExampleFolder: function (exampleFolder) {
                var me = this;
                OpencgaManager.files.search({
                    query: {
                        sid: Cookies('bioinfo_sid'),
                        studyId: me.$.outdir.selectedStudy.id,
                        name: exampleFolder

                    },
                    request: {
                        success: function (response) {
                            if (response.response[0].errorMsg === '' || response.response[0].errorMsg == null) {
                                me.$.outdir.selectedFile = response.response[0].result[0];
                                if (response.response[0].result.length == 0) {
                                    OpencgaManager.files.createFolder({
                                        query: {
                                            sid: Cookies('bioinfo_sid'),
                                            studyId: me.$.outdir.selectedStudy.id,
                                            folder: exampleFolder

                                        },
                                        request: {
                                            success: function (response) {
                                                if (response.response[0].errorMsg === '' || response.response[0].errorMsg == null) {
                                                    me.$.outdir.selectedFile = response.response[0].result[0];
                                                } else {

                                                }
                                            },
                                            error: function () {
                                                alert('Server error, try again later.');
                                            }
                                        }
                                    });
                                }
                            }
                        },
                        error: function () {
                            alert('Server error, try again later.');
                        }
                    }
                });
            }
        });
    </script>
</polymer-element>
