<polymer-element name="jso-rnaseq-norm-result" attributes="jobItem">
    <template>
        <link rel="stylesheet" href="../sortable-table.css">
        <style>
            :host {
                display: block;
                /*position: relative;*/
                background-color: white;
            }

            .data {
                margin-left: 20px;
            }

            .level-0 {
                /*border: 1px solid grey;*/
                padding: 20px;

            }

            .level-0 > .headerTitle {
                font-size: 15pt;
                font-weight: bold;
                padding: 5px;
            }

            .message > label {
                margin-right: 10px;
            }

            .message > label:after {
                content: ':';
            }

            .message > .messageValue {
                font-size: 9pt;
                font-weight: bold;
                font-style: italic;
                color: #55f;
                line-height: 21px;

            }

            .file > label {
                margin-right: 10px;
            }

            .file > a {
                font-size: 9pt;
                font-weight: bold;
                font-style: italic;
                color: #55f;
            }

            sortable-table::shadow thead tr th {
                /*width: 1000px;*/
                white-space: inherit;
                overflow: auto;
                text-overflow: inherit;

            }

            .output {
                margin: 10px;
                /*width: 1000px;*/
                background-color: white;
                border-radius: 5px;
                padding: 20px;
            }

            .loading {
                font-size: 20px;
                margin: 20px 50px;
            }
        </style>

        <template if="{{significativeResults == 'loading'}}">
            <div class="loading">
                <font-awesome icon="spinner" animation="spin" style="margin-right: 5px;"></font-awesome>
                Loading result...
            </div>
        </template>
        <template if="{{significativeResults != 'loading'}}">

            <div class="output">
                <h1> RNASeq Normalization</h1>

                <jso-job-info-widget jobItem="{{jobItem}}"></jso-job-info-widget>

                <div class="level-0">
                    <div class="headerTitle">Input parameters</div>
                    <div class="data">
                        <div class="message" horizontal="" layout="">
                            <label>Data file</label>

                            <div class="messageValue">{{dataFile}}</div>
                        </div>
                        <template if="{{glFile!=''}}">
                            <div class="message" horizontal="" layout="">
                                <label>Gene length file</label>

                                <div class="messageValue">{{glFile}}</div>
                            </div>
                        </template>
                        <template if="{{significativeResults == 'true'}}">
                            <div class="message" horizontal="" layout="">
                                <label>Method</label>


                                <div class="messageValue">{{method}}</div>
                            </div>
                        </template>

                    </div>
                </div>


                <div class="level-0">
                    <template if="{{significativeResults == 'false'}}">
                        <div class="headerTitle">No normalized data results</div>
                        <div class="data">
                            This is maybe due to incorrect input. For more info about proper inputs, refer to the
                            <a href="https://github.com/babelomics/babelomics/wiki/data-matrix-expression" target="_blank">documentation</a>.
                            You can also download the example file.
                            <br>
                            For more detailed information you can download the log file:
                            <div class="file"><label>Log output file:</label>
                                <a href="{{logOutputFile}}" target="_blank">log_output.txt</a>
                            </div>
                            <div class="file"><label>Log error file:</label>
                                <a href="{{logErrorFile}}" target="_blank">log_error.txt</a>
                            </div>
                            If error persist, please contact babelomics crew at babelomics@cipf.es

                        </div>
                    </template>
                    <template if="{{significativeResults == 'true'}}">

                        <div class="headerTitle">Normalized data results</div>
                        <div class="data">
                            <template if="{{glFile!=''}}">
                                <div flex horizontal layout>
                                    <div>
                                        <h4>RNA composition before normalization</h4>
                                        <img src="{{RNAComposition_beforeNorm}}">
                                    </div>
                                    <div>
                                        <h4>RNA composition after normalization</h4>
                                        <img src="{{RNAComposition_afterNorm}}">
                                    </div>
                                </div>
                            </template>
                            <div flex horizontal layout>
                                <div>
                                    <h4>Boxplot expression values before normalization</h4>
                                    <img src="{{boxplot_beforeNorm}}">
                                </div>
                                <div>
                                    <h4>Boxplot expression values after normalization</h4>
                                    <img src="{{boxplot_afterNorm}}">
                                </div>
                            </div>
                            <div class="file"><label>File</label>
                                <a href="{{normalizedFileUrl}}" download="normalized_results.txt">normalized_results.txt</a>
                            </div>
                            <template if="{{loadingTable}}">
                                <div>
                                    <font-awesome icon="spinner" animation="spin"></font-awesome>
                                    Loading table...
                                </div>
                            </template>

                            <sortable-table id="rnanorm-table"
                                            data="{{data}}"
                                            columns="{{columns}}"
                                            footerTemplate="{{footerTemplate}}"
                                            pageSize="{{pageSize}}"
                                            flex>
                            </sortable-table>
                            <jso-redirection titleRed=""
                                             fileName=""
                                             fileUrl=""
                                             buttonLabel="Send to edit"
                                             args="{{normalizedFileUrl_args}}" id="">

                            </jso-redirection>
                        </div>
                    </template>
                </div>
            </div>
        </template>
    </template>
    <script>
        Polymer({
            created: function () {
                this.significativeResults = "loading";
                this.columns = [];
                this.data = [];
                this.dataFile = "";
                this.glFile = "";

                this.loadingTable = true;

            },

            parseCommandLine: function () {
                this.clearFields();
                var fields = this.jobItem.commandLine.split(" ");
                for (var i = 0; i < fields.length; i++) {
                    if (fields[i] == "--glfile") {
                        var fileName = fields[i + 1].split("/");
                        this.glFile = fileName[fileName.length - 1];
                    }
                    if (fields[i] == "--datafile") {
                        var fileName = fields[i + 1].split("/");
                        this.dataFile = fileName[fileName.length - 1];
                    }
//                    if (fields[i] == "--method") {
//                        this.method = fields[i + 1];
//                    }
                }

            }
            ,
            clearFields: function () {
                this.dataFile = "";
                this.method = "getting method... ";
                this.glFile = "";
            }
            ,
            jobItemChanged: function (oldV, newV) {
                this.parseCommandLine();
                /** get url **/
                var me = this;
                OpencgaManager.files.filesByFolder({
                    id: me.jobItem.outDirId,
                    query: {
                        sid: Cookies("bioinfo_sid")
                    },
                    request: {
                        success: function (response) {

                            if (response.response[0].errorMsg === '' || response.response[0].errorMsg == null) {
                                var fileList = response.response[0].result;
                                for (var i = 0; i < fileList.length; i++) {
                                    var fileName = fileList[i].name;
                                    if (fileName == "normalize_results.txt") {
                                        me.significativeResults = 'true';
                                        me.normalizedFileUrl = Utils.getUrl(fileList[i].id);
                                        me.getFileContent(function (content) {
                                            me.parseTable(content);
                                        }, fileList[i].id);
                                        me.normalizedFileUrl_args = {
                                            tool: "edit",
                                            inputFile: fileList[i]
                                        };
                                    }
                                    if (fileName == "RNAComposition_afterNorm.png") {
                                        me.RNAComposition_afterNorm = Utils.getUrl(fileList[i].id);
                                    }
                                    if (fileName == "RNAComposition_beforeNorm.png") {
                                        me.RNAComposition_beforeNorm = Utils.getUrl(fileList[i].id);
                                    }
                                    if (fileName == "boxplot_beforeNorm.png") {
                                        me.boxplot_beforeNorm = Utils.getUrl(fileList[i].id);
                                    }
                                    if (fileName == "boxplot_afterNorm.png") {
                                        me.boxplot_afterNorm = Utils.getUrl(fileList[i].id);
                                    }
                                    if (fileName.indexOf("sge_out.job") >= 0) {
                                        me.logOutputFile = Utils.getUrl(fileList[i].id);
                                    }
                                    if (fileName.indexOf("sge_err.job") >= 0) {
                                        me.logErrorFile = Utils.getUrl(fileList[i].id);
                                    }
                                }
                                if (me.significativeResults != 'true')
                                    me.significativeResults = 'false';
                            }
                        },
                        error: function () {
                            me.message = 'Server error, try again later.';
                        }
                    }
                });
            }
            ,
            parseTable: function (content) {
                this.data = [];
                this.columns = [];
                var data = content.split("\n");
                /** get header **/
                var processColumns = true;
                var idxHeader = 0;
                for (var i = 0; i < data.length; i++) {
                    if (data[i] == "") continue;
                    if (data[i].indexOf("#") == 0) {
                        if (data[i].indexOf("method") >= 0) {
                            this.method = data[i].split(" ")[1];
                        }
                        idxHeader = i;
                        continue;
                    }
                    /** process columns **/
                    if (processColumns) {
                        processColumns = false;
                        var aux = data[idxHeader].split("\t");
                        for (var j = 0; j < aux.length; j++) {
                            this.columns.push({name: aux[j]})
                        }
                    }
                    var localData = data[i].split("\t");
                    var obj = new Object();
                    for (var j = 0; j < localData.length; j++) {
                        var value = localData[j];
                        if (isNaN(value))
                            obj[this.columns[j]["name"]] = value;
                        else {
                            if (!this.isInt(value))
                                obj[this.columns[j]["name"]] = Utils.formatNumber(value);
                            else
                                obj[this.columns[j]["name"]] = Utils.formatNumber(value);

                        }
                    }
                    this.data.push(obj);
                }

                this.pageSize = "10";
                this.footerTemplate = "simplePager";
                this.loadingTable = false;

            }
            ,
            isInt: function (n) {
                return n % 1 === 0;
            }
            ,

            getFileContent: function (callback, fileId) {
                OpencgaManager.files.content({
                    id: fileId,
                    query: {
                        sid: Cookies("bioinfo_sid")
                    },
                    request: {
                        success: function (response) {
                            callback(response)
                        },
                        error: function () {
                            this.message = 'Server error, try again later.';
                        }
                    }
                })
            }
        })
    </script>
</polymer-element>


