<!--
  ~ Copyright 2015 OpenCB
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<link rel="import" href="../../../lib/jsorolla/src/lib/cellbase/variation/cellbase-variantannotation-view.html">
<link rel="import" href="../../../lib/jsorolla/src/lib/opencga/variant/variant-browser-grid.html">

<dom-module id="cellbase-variation-view">
    <template>
        <style is="custom-style" include="jso-styles"></style>

        <div style="width: 90%">
            <ul id="myTabs" class="nav nav-tabs" role="tablist">
                <li role="presentation" class="active"><a href="#variationViewInfo" role="tab" data-toggle="tab">{{variationId}} Info</a></li>
                <li role="presentation"><a href="#variationViewGenomeContext" role="tab" data-toggle="tab">Genome Context</a></li>
                <!--<li role="presentation" class="active"><a href="#variationGenomeContext" role="tab" data-toggle="tab">Genome Context</a></li>-->
            </ul>

            <div class="tab-content" style="width: 90%">
                <div id="variationViewInfo" role="tabpanel" class="tab-pane active">
                    <variant-browser-grid cellbase-client="{{cellbaseClient}}" population-frequencies="{{populationFrequencies}}" protein-substitution-scores="{{proteinSubstitutionScores}}"
                                          consequence-types="{{consequenceTypes}}" query="[[query]]" search="[[search]]" variant="{{variant}}" style="font-size: 12px">
                    </variant-browser-grid>

                    <h3>Annotation</h3>
                    <cellbase-variantannotation-view cellbase-client="{{cellbaseClient}}" data="{{variant}}" prefix="variation"></cellbase-variantannotation-view>

                </div>

                <div role="tabpanel" class="tab-pane" id="variationViewGenomeContext">
                    <br>
                    <div id="variationGenomeViewer"></div>
                </div>
            </div>
        </div>

    </template>
    <script>
        Polymer({
            is: 'cellbase-variation-view',

            properties: {
                cellbaseClient: {
                    type: Object
                },
                variationId: {
                    type: String,
                    observer: '_variationIdChanged'
                },
                variationObj: {
                    type: Object
                },
                variant: {
                    type: String,
                    notify: true
                },
                populationFrequencies: {
                    type: Object
                },
                consequenceTypes: {
                    type: Object
                },
                proteinSubstitutionScores: {
                    type: Object
                }
            },
            _variationIdChanged: function(newValue, oldValue) {
                let _this = this;
                if (typeof this.cellbaseClient !== "undefined") {
                    this.cellbaseClient.getVariationClient(this.variationId, 'info', {}, {})
                        .then(function (response) {
                            let firstVariation = response.response[0].result[0];
                            if (typeof firstVariation !== "undefined") {
                                let region = new Region({chromosome: firstVariation.chromosome, start: firstVariation.start, end: firstVariation.end});
                                if (typeof _this.genomeViewer !== "undefined") {
                                    _this.genomeViewer.setRegion(region);
                                }
                            } else {
                                alert("Variation ID not valid: " + _this.variationId);
                            }
                            _this.variationObj = firstVariation;
                            _this.variant = firstVariation.chromosome + ":" + firstVariation.start + ":" + firstVariation.reference + ":" + firstVariation.alternate;
                        });
                }
            },
            attached: function() {
//                this.genomeViewer;
//                this.renderGenomeViewer();
            },
            renderGenomeViewer: function() {
                var region = new Region({chromosome: "13", start: 32889611, end: 32889611});
                this.genomeViewer = new GenomeViewer({
                    cellBaseHost: "http://bioinfo.hpc.cam.ac.uk/cellbase",
                    cellBaseVersion: 'v3',
                    target: this.$$('#variationGenomeViewer'),
//                    width: this.$$('#variationGenomeViewer').getBoundingClientRect().width,
                    width: 1200,
                    region: region,
                    availableSpecies: DEFAULT_SPECIES.vertebrates,
                    species: DEFAULT_SPECIES.vertebrates[0],
                    sidePanel: false,
                    autoRender: true,
                    resizable: true,
//        quickSearchResultFn:quickSearchResultFn,
//        quickSearchDisplayKey:,
                    karyotypePanelConfig: {
                        collapsed: false,
                        collapsible: true
                    },
                    chromosomePanelConfig: {
                        collapsed: false,
                        collapsible: true
                    },
                    navigationBarConfig: {
                        componentsConfig: {
//                restoreDefaultRegionButton:false,
//                regionHistoryButton:false,
//                speciesButton:false,
//                chromosomesButton:false,
//                karyotypeButton:false,
//                chromosomeButton:false,
//                regionButton:false,
//                zoomControl:false,
//                windowSizeControl:false,
//                positionControl:false,
//                moveControl:false,
//                autoheightButton:false,
//                compactButton:false,
//                searchControl:false
                        }
                    },
                    handlers: {
                        'region:change': function(e) {
                            console.log(e)
                        }
                    }
//        chromosomeList:[]
//            trackListTitle: ''
//            drawNavigationBar = true;
//            drawKaryotypePanel: false,
//            drawChromosomePanel: false,
//            drawOverviewTrackListPanel: false
                });
                var tracks = [];
                this.sequence = new FeatureTrack({
                    title: 'Sequence',
                    height: 25,
                    visibleRegionSize: 200,
                    renderer: new SequenceRenderer(),
                    dataAdapter: new CellBaseAdapter({
                        category: "genomic",
                        subCategory: "region",
                        resource: "sequence",
                        params: {},
                        species: this.genomeViewer.species,
                        cacheConfig: {
                            chunkSize: 100
                        }
                    })
                });
                tracks.push(this.sequence);
                this.gene = new GeneTrack({
                    title: 'Gene',
                    minHistogramRegionSize: 20000000,
                    maxLabelRegionSize: 10000000,
                    minTranscriptRegionSize: 200000,
                    height: 100,
                    renderer: new GeneRenderer({
                        handlers: {
                            'feature:click': function(e) {
                                console.log(e)
                            }
                        }
                    }),
                    dataAdapter: new CellBaseAdapter({
                        category: "genomic",
                        subCategory: "region",
                        resource: "gene",
                        species: this.genomeViewer.species,
                        params: {
                            exclude: 'transcripts.tfbs,transcripts.xrefs,transcripts.exons.sequence'
                        },
                        cacheConfig: {
                            chunkSize: 100000
                        }
                    })
                });
                tracks.push(this.gene);
                var renderer = new FeatureRenderer(FEATURE_TYPES.gene);
                renderer.on({
                    'feature:click': function(event) {
                        // feature click event example
                        console.log(event)
                    }
                });
                var gene = new FeatureTrack({
//        title: 'Gene overview',
                    minHistogramRegionSize: 20000000,
                    maxLabelRegionSize: 10000000,
                    height: 100,
                    renderer: renderer,
                    dataAdapter: new CellBaseAdapter({
                        category: "genomic",
                        subCategory: "region",
                        resource: "gene",
                        params: {
                            exclude: 'transcripts,chunkIds'
                        },
                        species: this.genomeViewer.species,
                        cacheConfig: {
                            chunkSize: 100000
                        }
                    })
                });
                this.genomeViewer.addOverviewTrack(gene);
                this.snp = new FeatureTrack({
                    title: 'SNP',
                    featureType: 'SNP',
                    minHistogramRegionSize: 12000,
                    maxLabelRegionSize: 3000,
                    height: 120,
                    renderer: new FeatureRenderer(FEATURE_TYPES.snp),
                    dataAdapter: new CellBaseAdapter({
                        category: "genomic",
                        subCategory: "region",
                        resource: "snp",
                        params: {
                            exclude: 'transcriptVariations,xrefs,samples'
                        },
                        species: this.genomeViewer.species,
                        cacheConfig: {
                            chunkSize: 10000
                        }
                    })
                });
                tracks.push(this.snp);
                /*************************/
//                var customTrack = new FeatureTrack({
//                    title: 'custom track',
//                    minHistogramRegionSize: 12000,
//                    maxLabelRegionSize: 3000,
//                    height: 120,
//                    renderer: new FeatureRenderer(),
//                    dataAdapter: new FeatureTemplateAdapter({
//                        multiRegions: true,
//                        histogramMultiRegions: false,
//                        uriTemplate: 'https://dcc.icgc.org/api/browser/gene?segment={region}&resource=gene',
//                        cacheConfig: {
//                            chunkSize: 100000
//                        }
//                    })
//                });
//                tracks.push(customTrack);
                /*************************/
                this.genomeViewer.addTrack(tracks);
                this.genomeViewer.draw();

            }
        });
    </script>
</dom-module>
