<polymer-element name="jso-intact-import" extends="jso-window" attributes="networkViewer">
    <template>
        <style>
            :host {
                display: block;
                position: fixed;
                box-sizing: border-box;
                background-color: #FFFFFF;

                width: 680px;
                height: 420px;
            }

            #panel {
                width: 100%;
                height: 100%;
                /*background-color: #FFFFFF;*/
            }

            .checkbox {
                width: 25px;
            }

            .checkbox::after {
                font-family: 'FontAwesome';
                content: ' \00a0'
            }

            .checkbox[data-checked]::after {
                content: '\f00c'
            }

            .selbox {
                box-sizing: border-box;
                overflow-y: auto;
                border: 1px solid #d3d3d3;
                background-color: #FFF;
            }

            .selitem {
                padding: 2px 5px;
            }

            .selitem[data-checked=true] {
                background-color: #ddd;
                /*background-color: #435f7a;*/
                /*background-color: #f07746;*/
                /*color: #fff;*/
            }

            textarea {
                resize: none;
                margin: 3px;
            }
        </style>
        <div class="panel panel-shadow" id="panel" vertical layout>
            <div id="header" class="header" horizontal layout
                 on-mousedown="{{handleHeaderMouseDown}}"
                 on-mouseup="{{handleHeaderMouseUp}}">
                <div class="text">Import IntAct</div>
                <div class="headeractions" horizontal end-justified layout flex>
                    <!--<div class="text headerexpand" expanded?={{expanded}} on-click="{{handleExpand}}"></div>-->
                    <div class="text headerclose" on-click="{{handleClose}}"></div>
                </div>
            </div>
            <div class="container" flex horizontal layout>

                <div vertical layout style="width:230px;padding:5px;">

                    <label style="margin-top: 2px;">Species:</label>

                    <div class="selbox" flex>
                        <template repeat="{{spe in species}}">
                            <div class="selitem"
                                 data-checked="{{ speciesSelected == spe }}"
                                 on-click="{{handleSpeciesSelect}}">{{spe.name}}
                            </div>
                        </template>
                    </div>

                    <label style="margin-top: 10px;">Attributes:</label>

                    <div class="selbox" flex>
                        <template repeat="{{column in networkViewer.vAttr.columns}}">
                            <div class="selitem"
                                 data-checked="{{ columnSelected == column.name }}"
                                 on-click="{{handleEditSelect}}">{{column.title}}
                            </div>
                        </template>
                    </div>

                    <label style="margin-top: 10px;">Input:</label>

                    <form>
                        <label class="control">
                            <input type="radio" checked="{{selectedMode == 'nodes'}}" on-change="{{handleSelectNodesList}}">
                            <span>Network nodes</span>
                        </label>
                        <label class="control">
                            <input type="radio" checked="{{selectedMode == 'selection'}}" on-change="{{handleSelectSelectionList}}">
                            <span>Network selection</span>
                        </label>
                        <label class="control">
                            <input type="radio" checked="{{selectedMode == 'text'}}" on-change="{{handleSelectTextList}}">
                            <span>List from text</span>
                        </label>

                        <div class="button action" style="width:150px;margin-top: 3px;" on-click="{{handleSelectFileList}}">
                            List from file ...
                        </div>
                    </form>
                </div>


                <textarea id="textarea" flex></textarea>

            </div>

            <div class="footer" horizontal layout>
                <div class="text" horizontal layout flex>
                    <template if="{{loading}}">
                        <font-awesome icon="spinner" animation="spin" style="margin-right: 5px;"></font-awesome>
                    </template>
                    <div>{{message}}</div>
                </div>
                <div horizontal end-justified layout>
                    <div class="button action" on-click="{{handleGo}}" style="width:100px;">Search</div>
                </div>
            </div>
            <input on-change={{handleInputFileChange}} id="inputFile" type="file" hidden>
        </div>
    </template>
    <script>
        Polymer({
            created: function () {
                this.species = [
                    {name: "Homo sapiens", value: "hsapiens"},
                    {name: "Mus musculus", value: "mmusculus"},
                    {name: "Rattus norvegicus", value: "rnorvegicus"},
                    {name: "Bos taurus", value: "btaurus"},
                    {name: "Gallus gallus", value: "ggallus"},
                    {name: "Sus scrofa", value: "sscrofa"},
                    {name: "Canis familiaris", value: "cfamiliaris"},
                    {name: "Drosophila melanogaster", value: "dmelanogaster"},
                    {name: "Caenorhabditis elegans", value: "celegans"},
                    {name: "Saccharomyces cerevisiae", value: "scerevisiae"},
                    {name: "Danio rerio", value: "drerio"},
                    {name: "Schizosaccharomyces pombe", value: "spombe"},
                    {name: "Escherichia coli", value: "ecoli"},
                    {name: "Human immunodeficiency virus 1", value: "hiv-1"},
                    {name: "Influenza A virus", value: "flu-a"},
                    {name: "Clostridium botulinum", value: "cbotulinum"},
                    {name: "Arabidopsis thaliana", value: "athaliana"},
                    {name: "Plasmodium falciparum", value: "pfalciparum"},
                    {name: "Dictyostelium discoideum", value: "ddiscoideum"},
                    {name: "Mycobacterium tuberculosis", value: "mtuberculosis"},
                    {name: "Neisseria meningitidis serogroup B", value: "nmeningitidis"},
                    {name: "Chlamydia trachomatis", value: "ctrachomatis"},
                    {name: "Oryza sativa", value: "osativa"},
                    {name: "Toxoplasma gondii", value: "tgondii"},
                    {name: "Xenopus tropicalis", value: "xtropicalis"},
                    {name: "Salmonella typhimurium", value: "styphimurium"},
                    {name: "Taeniopygia guttata", value: "tguttata"},
                    {name: "Staphylococcus aureus N315", value: "saureus"}
                ];

                this.speciesSelected = this.species[0];
                this.columnSelected = "id";

                this.selectedMode = 'text';
            },
            observe: {
                'networkViewer.vAttr.selected': 'handleSelectionChange',
                'networkViewer.vAttr.data': 'handleNodesChange'
            },
            handleEditSelect: function (e) {
                this.columnSelected = e.target.templateInstance.model.column.name;
            },
            handleSpeciesSelect: function (e) {
                this.speciesSelected = e.target.templateInstance.model.spe;
            },
            handleItemSelect: function (e) {
                var item = e.target.templateInstance.model.item;
                item.selected = !item.selected;
            },
            handleSelectNodesList: function () {
                this.selectedMode = 'nodes';
                var value = '';
                for (var i = 0; i < this.networkViewer.vAttr.data.length; i++) {
                    var row = this.networkViewer.vAttr.data[i];
                    value += row[this.columnSelected] + '\n';
                }
                this.$.textarea.value = value;
            },
            handleNodesChange: function () {
                if (this.selectedMode == 'nodes') {
                    this.handleSelectNodesList();
                }
            },
            handleSelectSelectionList: function () {
                this.selectedMode = 'selection';
                var value = '';
                for (var i = 0; i < this.networkViewer.vAttr.selected.length; i++) {
                    var row = this.networkViewer.vAttr.selected[i];
                    value += row[this.columnSelected] + '\n';
                }
                this.$.textarea.value = value;
            },
            handleSelectionChange: function () {
                if (this.selectedMode == 'selection') {
                    this.handleSelectSelectionList();
                }
            },
            handleSelectTextList: function () {
                this.$.textarea.value = '';
                this.selectedMode = 'text';
            },
            handleSelectFileList: function () {
                this.$.inputFile.click();
            },
            handleInputFileChange: function (e) {
                var me = this;
                var file = this.$.inputFile.files[0];
                var reader = new FileReader();
                reader.onload = function (evt) {
                    me.selectedMode = 'file';
                    var content = evt.target.result;
                    me.$.textarea.value = content;
                };
                reader.readAsText(file);
                e.currentTarget.value = null;
            },
            handleGo: function () {
                var me = this;
                var queryList = this.$.textarea.value.split('\n');
                if (this.speciesSelected != null && queryList.length > 0) {
                    this.getGraph(this.speciesSelected.value, queryList, function (graph) {
                        me.networkViewer.setGraph(graph);
                        me.networkViewer.setLayout('Force directed');
                        me.loading = false;
                        me.message = "Information has been saved as nodes and edges";
                    });
                } else {
                    this.message = "Please select one species and one attribute";
                }
            },

            getGraph: function (speciesCode, idList, successFunction) {
                var me = this;

                var graph = new Graph();
//                _this.progress.updateProgress(0.1, 'Requesting data');

                this.loading = true;
                this.message = "Retrieving data...";
                CellBaseManager.get({

                    species: speciesCode,
                    category: 'network',
                    subCategory: 'protein',
                    resource: 'all',
                    params: {
                        interactor: idList.join(','),
                        include: "interactorA.id,interactorB.id"
                    },
                    success: function (data) {
                        console.log(data)
                        var interactions = data.response.result;

                        for (var j = 0; j < interactions.length; j++) {
                            var interaction = interactions[j];
                            var sourceName = interaction.interactorA.id;
                            var edgeRelation = 'pp';
                            var targetName = interaction.interactorB.id;


                            var sourceVertex = new Vertex({
                                id: sourceName,
                                position: new Point(0, 0),
                                renderer: new CircosVertexRenderer(me.networkViewer.vertexDefaults)
                            });
                            if (!graph.addVertex(sourceVertex)) {
                                sourceVertex = graph.getVertexById(sourceName);
                            }

                            var targetVertex = new Vertex({
                                id: targetName,
                                position: new Point(0, 0),
                                renderer: new CircosVertexRenderer(me.networkViewer.vertexDefaults)
                            });
                            if (!graph.addVertex(targetVertex)) {
                                targetVertex = graph.getVertexById(targetName);
                            }

                            var edgeId = sourceVertex.id + '_' + edgeRelation + '_' + targetVertex.id;
                            var edge = new Edge({
                                id: edgeId,
                                relation: edgeRelation,
                                source: sourceVertex,
                                target: targetVertex,
                                renderer: new DefaultEdgeRenderer(me.networkViewer.edgeDefaults)
                            });
                            graph.addEdge(edge);
//                            var sourceVertex = me.networkViewer.createVertex(0, 0, sourceName);
//                            var targetVertex = me.networkViewer.createVertex(0, 0, targetName);
//                            me.networkViewer.createEdge(sourceVertex, targetVertex, edgeRelation);
                        }
                        successFunction(graph);
                    }
                });
            }

        });
    </script>
</polymer-element>