<polymer-element name="jso-survival" 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>
                Differential expression: survival
                <a target="_blank" href="">
                    <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}}">Survival demo (Cox test)</div>
                    <div class="button action" on-click="{{handleDownloadFile}}" data-example="survival_ordered.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 time and series variables</div>
                <div class="formcontent">
                    Time variable name:
                    <!--<jso-class-viewer id="jsoClassViewerTime" contentFile="{{contentFile}}" loadedMainSelect="{{loadedMainSelect}}"-->
                    <!--loadedChildrenSelect="{{loadedChildrenSelect}}" changedChildrenSelect="{{changedChildrenSelect}}" childrenDisplay="false"-->
                    <!--variableTypes="NUMERIC"></jso-class-viewer>-->
                    <jso-class-viewer id="jsoClassViewerTime" contentFile="{{contentFile}}" on-main-select="{{loadedMainSelect}}" childrenDisplay="false"
                                      variableTypes="NUMERIC"></jso-class-viewer>
                    Censored variable name:
                    <!--<jso-class-viewer id="jsoClassViewerCensored" contentFile="{{contentFile}}" loadedMainSelect="{{loadedMainSelect}}"-->
                                      <!--loadedChildrenSelect="{{loadedChildrenSelect}}" changedChildrenSelect="{{changedChildrenSelect}}" childrenDisplay="false"></jso-class-viewer>-->
                    <jso-class-viewer id="jsoClassViewerCensored" contentFile="{{contentFile}}" on-main-select="{{loadedMainSelect}}" childrenDisplay="false"></jso-class-viewer>

                </div>
            </div>
            <div class="formbox">
                <div class="formtitle">Test</div>
                <div class="formcontent">
                    <div id="testDiv">
                        Cox test used
                    </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 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: 50px">
                </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 = 'survival';
                this.toolName = "survival";
                this.description = "Job description";

                this.censored_class = "";
                this.correction = "";
                this.p_value = 0.05;
                this.test = "cox";
                this.time_class = "";
            },
            handleDownloadFile: function (e) {
                Utils.downloadExampleFile(this.toolName, e.currentTarget.dataset.example);
            },

            handleFileSelect: function (e) {
                var file = e.detail.file;
                if (file.type == "FILE")
                    this.getContentFile(file);
            },
            handleForm: function () {

                this.launchJob();
            },
            launchJob: function () {
                var me = this;
                if (!Utils.basicValidationForm(this)) {
                    return;
                }

                if (this.$.p_value.value == "" || isNaN(this.$.p_value.value)) {
                    alert("Sorry. P is value not a number. ");
                    return;
                }
                this.censored_class = this.$.jsoClassViewerCensored.getMainSelect().value;
                this.time_class = this.$.jsoClassViewerTime.getMainSelect().value;
                if (this.censored_class == "none" || this.time_class == "none") {
                    alert("Sorry: Either censored class or time class are missing. Please select them.");
                    return;
                }
                if (this.censored_class == this.time_class) {
                    alert("Sorry: Censored class and time class can't be the same.");
                    return;
                }
                this.correction = this.shadowRoot.querySelector('input[name="correction"]:checked').value;
                var query = {
                    sid: Cookies("bioinfo_sid"),
                    studyId: this.selectedStudy.id,
                    toolId: this.toolName,
                    outdir: this.$.outdir.selectedFile.id,
                    name: this.jobName,
                    description: this.description,
                    "censored-class": this.censored_class,
                    "time-class": this.time_class,
                    dataset: this.$.inputFile.selectedFile.id,
                    test: this.test,
                    correction: this.correction,
                    "p-value": this.$.p_value.value
                };
                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.selectedOption = "jobLaunched"
                            } else {
                                me.message = response.response[0].errorMsg;
                            }
                        },
                        error: function () {
                            me.message = 'Server error, try again later.';
                        }
                    }
                })
            },
            loadExample1: function (e) {
                this.jobName = "Survival demo (Cox test)";
                this.description = "Differential expression - Survival demo (Cox test)";
                this.newFolderName = "surv_" + Math.floor((Math.random() * 100) + 1);
                this.$.inputFile.selectedFile = {id: "example_survival_ordered.txt", path: "survival_ordered.txt", type: "FILE"};
                this.p_value = 0.05;
                this.$.correction_1.checked = true;

                this.getContentFile(this.$.inputFile.selectedFile);


                var exampleFolder = "survival_demo";
                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.');
                        }
                    }
                });
            },
            loadedMainSelect: function () {
                /** This is mainly for the examples **/
                var selectCensored = this.$.jsoClassViewerCensored.getMainSelect();
                var selectTime = this.$.jsoClassViewerTime.getMainSelect();
                if (this.$.inputFile.selectedFile.id == "example_survival.txt") {
                    selectCensored.value = "censored";
                    selectTime.value = "time";
                }
                if (this.$.inputFile.selectedFile.id == "example_survival_ordered.txt") {
                    selectCensored.value = "censored";
                    selectTime.value = "time";
                }
            },
            loadExampleFile: function (exampleFileName) {
                var me = this;
                OpencgaManager.files.contentExample({
                    query: {
                        toolName: this.toolName,
                        fileName: exampleFileName
                    },
                    request: {
                        //method: 'POST',
                        success: function (response) {
                            me.contentFile = response;
                        },
                        error: function () {
                            me.message = 'Server error, try again later.';
                        }
                    }
                })
            },
            getContentFile: function (file) {
                this.$.jsoClassViewerTime.loading = true;
                this.$.jsoClassViewerCensored.loading = true;

                var me = this;
                if (String(file.id).indexOf("example_") >= 0) {
                    this.loadExampleFile(file.path);
                } else {
                    OpencgaManager.files.content({
                        id: file.id,
                        query: {
                            sid: Cookies('bioinfo_sid')
                        },
                        request: {
                            //method: 'POST',
                            success: function (response) {
                                me.contentFile = response;
                            },
                            error: function () {
                                var message = 'Server error, try again later.';
                            }
                        }
                    })
                }
            }
        });
    </script>
</polymer-element>
