<polymer-element name="jso-protein-viewer" attributes="nodes speciesSelection nodeSelection jobResult">
    <template>
        <link rel="stylesheet" href="../sortable-table.css">
        <style>

            jso-network-viewer {
                height: 800px;
                border: 1px solid #d3d3d3;
            }

            /*TODO temporal fix*/
            jso-network-viewer::shadow jso-nv-layout {
                /*height: calc(100% - 126px);*/
            }
        </style>
        <div id="networkWidget">
            <template if="{{speciesSelection == ''}}">
                <div style="margin-bottom: 5px">
                    <label>Species:</label> <div class="select">
                        <select id="species" value="hsapiens" on-change="{{handleSpecies}}">
                            <template repeat="{{spe in species}}">
                                <option value="{{spe.value}}">
                                    {{spe.name}}
                                </option>
                            </template>
                        </select>
                    </div>
                </div>
            </template>
            <template if="{{nodeSelection == true}}">

                <div style="margin-bottom: 5px" flex horizontal layout>
                    <label>Select number of nodes in the top list of the differential expression result</label>
                    <input type="text" style="margin-right: 2px; width: 30px" value="{{networkNodesTop}}">
                </div>
                <div style="margin-bottom: 5px" flex horizontal layout>
                    <label>Select number of nodes in the bottom list of the differential expression result</label>
                    <input type="text" style="margin-right: 2px; width: 30px" value="{{networkNodesBottom}}">
                </div>
                <div class="button action"
                     style="width: 110px; margin-top: 5px; margin-bottom: 5px; "
                     on-click="{{nodesChanged}}">Draw network
                </div>
            </template>
        </div>

        <template if="{{jobResult.networkViewer}}">
            <div horizontal layout>
                <div>
                    <input type="text" value="{{sessionName}}">
                </div>
                <div class="button action" style="margin-left:5px" on-click="{{handleSaveSessionToCellMaps}}">
                    Save network as Cell Maps session
                </div>
            </div>
            <div horizontal layout>
                <label>
                    {{saveMessage}}
                </label>
                <template if="{{saveMessageOk}}">
                    <div class="button action" on-click="{{handleOpenCellMapsSessionManager}}">
                        Open Cell Maps session Manager
                    </div>
                </template>
            </div>
            <br>
        </template>

        <jso-network-viewer id="networkViewer" lite="true"></jso-network-viewer>
        </div>
        <label>You can move the canvas using CTRL+CLICK or using the <b>Move</b> mode
            <font-awesome icon="arrows"></font-awesome>
        </label>

    </template>
    <script>
        Polymer({
            created: function () {

                this.ids = [];
                this.networkNodesTop = 10;
                this.networkNodesBottom = 10;
                this.species = SPECIES;
                this.speciesSelection = "";
                this.nodeSelection = true;

                this.sessionName = "";
                this.saveMessage = "";
                this.saveMessageOk = false;
            },
            domReady: function () {
                this.$.networkViewer.$.nodeRender.setAttribute('hidden', '');
                this.$.networkViewer.$.edgeRender.setAttribute('hidden', '');
            },

            nodesChanged: function (oldV, newV) {
                var me = this;
                this.$.networkViewer.startOver();
                if (this.networkNodesTop == "" || isNaN(this.networkNodesTop))
                    this.networkNodesTop = 0;
                if (this.networkNodesBottom == "" || isNaN(this.networkNodesBottom))
                    this.networkNodesBottom = 0;

                this.nodesToRender = this.nodes.slice(0, this.networkNodesTop);
                this.nodesToRender = this.nodesToRender.concat(this.nodes.slice(this.nodes.length - this.networkNodesBottom, this.nodes.length));
                if (this.nodesToRender.length == 0)
                    return;
                var nodesMap = {};
                for (var i = 0; i < this.nodesToRender.length; i++) {
                    var node = this.nodesToRender[i];
                    nodesMap[node] = true;
                }

                var intactImport = this.$.networkViewer.$.intactImport;
                var cellbaseAttributeImport = this.$.networkViewer.$.cellbaseAttributeImport;

                if (this.speciesSelection == "")
                    var species = Utils.getSpecies(this.$.species.value, SPECIES);
                else
                    var species = Utils.getSpecies(this.speciesSelection, SPECIES);


                var xrefDatabase = species.dbname;
                var xrefDatabaseId = xrefDatabase + "id";
                console.log(this.nodesToRender);
//                var species = "hsapiens";
                intactImport.getGraph(species.value, this.nodesToRender, function (graph) {
                    if (graph.vertices.length == 0) {
                        for (var i = 0; i < me.nodesToRender.length; i++) {
                            var node = me.nodesToRender[i];
                            me.$.networkViewer.createVertex(0,0,node);
                        }
                        me.$.networkViewer.setLayout('Force directed');
                        return;
                    }
                    me.$.networkViewer.setGraph(graph);
                    me.$.networkViewer.setLayout('Force directed');

                    cellbaseAttributeImport.uncheckAllDatabases();
                    cellbaseAttributeImport.checkDatabase(xrefDatabase);

                    cellbaseAttributeImport.retrieveData('id', species.value, function () {
                        
                        me.$.networkViewer.selectVertexDefaultLabelAttribute(xrefDatabaseId);
                        cellbaseAttributeImport.uncheckAllDatabases();

                        for (var i = 0; i < me.$.networkViewer.vAttr.data.length; i++) {
                            var row = me.$.networkViewer.vAttr.data[i];
                            var val = row[xrefDatabaseId];
                            if (!val || val == '') {
                                row[xrefDatabaseId] = row['id'];
                            }
                            else {
                                var vals = val.split(",");
                                var newVals = [];
                                for (var j = 0; j < vals.length; j++) {
                                    var v = vals[j];
                                    if (nodesMap[v] === true) {
                                        newVals.push(v);
                                    }
                                }
                                row[xrefDatabaseId] = newVals.join(',')
                            }
                            if (nodesMap[row[xrefDatabaseId]] == true) {
                                var vertex = me.$.networkViewer.graph.getVertexById(row['id']);
                                vertex.renderer.set("color", '#f99494');
                            }
                        }
                    });
                });


            },
            handleSaveSessionToCellMaps: function (e) {
                var saved = this.jobResult.networkViewer.$.sessionManager.saveSession(this.$.networkViewer, this.sessionName + ' - ' + this.jobResult.jobItem.name);
                if (saved) {
                    this.saveMessage = "Saved as " + this.sessionName + ", you can go back to Cell Maps and load the network using the session manager inside File menu.";
                    this.sessionName = '';
                    this.saveMessageOk = true;
                } else {
                    this.saveMessage = this.sessionName + 'already exists.';
                    this.saveMessageOk = false;
                }
            },
            handleOpenCellMapsSessionManager: function () {
                this.jobResult.selectedOption = "";
                this.jobResult.networkViewer.selectedMenu = "session-manager";
            }
        })
    </script>
</polymer-element>

