{% extends 'base.html.j2' %}

{% block head %}
<title>{{ title }}</title>
{% endblock %}

{% block content %}

<div class="row flex-nowrap">
    <div class="col-md-4 col-12 menu">
        <div class="card">
            <div class="card-header">
                <a class="pull-right" role="button"><i class="fa" id="hide-show"></i></a>
                <h1><a href="index.html" class="link-unstyled">{{ title }}</a></h1>
                <p><a id="download" href="#">Download SVG</a> | <a id="degenes" href="#">Download shown gene list</a></p>

                <nav>
                    <div class="nav nav-tabs card-header-tabs" role="tablist">
                        <a data-toggle="tab" role="tab" class="nav-item nav-link active" href="#geneset">Gene Sets</a>
                        <a data-toggle="tab" role="tab" class="nav-item nav-link" href="#genes">Genes</a>
                        <a data-toggle="tab" role="tab" class="nav-item nav-link" href="#structure">Structure</a>
                        <a data-toggle="tab" role="tab" class="nav-item nav-link" href="#style">Style</a>
                    </div>
                </nav>

            </div>

            <div class="tab-content">
                <div class="tab-pane card-body fade show active" id="geneset" role="tabpanel">
                    <input class="form-control" id="chooseGeneSet" placeholder="Choose a Gene Set..." />
                    <br>
                    <hr>
                    <br>
                    <input class="form-control" id="findGeneSet" placeholder="Search for Gene Sets by Gene..." />
                </div>

                <div class="tab-pane card-body fade" id="genes" role="tabpanel">
                    <div contenteditable="true" class="form-control" id="chooseGenes" placeholder="Choose Genes..."></div>
                </div>

                <div class="tab-pane card-body fade" id="structure" role="tabpanel">

                    <div class="row"><div class="col">
                        <div><b><label>Datasets</label></b></div>
                        <div class="form-group" id="datasets"></div>
                    </div></div>

                    <br>

                    <div class="row"><div class="col">
                        <div><b><label>Sort By</label></b></div>
                        <div class="form-group" id="sort_by"></div>
                    </div></div>

                    <br>

                    <b><label>Filter by</label></b>
                    <div class="row">
                        <div class="form-group col-6">
                            <label for="q_threshold">-log₁₀ q-value threshold:</label>
                            <input type="number" class="form-control" id="q_threshold" value="0" />
                        </div>
                        <div class="form-group col-6">
                            <label for="fc_threshold">log₂ fold-change threshold:</label>
                            <input type="number" class="form-control" id="fc_threshold" value="0" />
                        </div>
                    </div>
                </div>

                <div class="tab-pane card-body fade" id="style" role="tabpanel">

                    <div class="row"><div class="col">
                        <div><b><label>Colors</label></b></div>
                        <table><tbody id="dataset_colors"></tbody></table>
                    </div></div>

                    <br>

                    <div><input type="checkbox" id="single_color" value="single_color"><label for="single_color">Single color (up and down) for each dataset.</label></div>

                    <br>

                    <b><label>Legends</label></b>
                    <div><input type="checkbox" id="show_legends" value="show_legends"><label> Show legends </label></div>

                    <br>

                    <b><label>Spacing</label></b>
                    <div>
                        <label for="row_thickness">Row Thickness</label>
                        <input type="range" id="row_thickness" name="row_thickness" min="10" max="72" step="1" value="24" style="position: relative; top: 3px; display: inline">
                    </div>
                    <div>
                        <label for="margin_between_bars">Margin Between Bars</label>
                        <input type="range" id="margin_between_bars" name="margin_between_bars" min="0" max="8" step="0.01" value="1" style="position: relative; top: 3px; display: inline">
                    </div>
                    <div>
                        <label for="margin_between_rows">Margin Between Rows</label>
                        <input type="range" id="margin_between_rows" name="margin_between_rows" min="2" max="30" step="0.1" value="10" style="position: relative; top: 3px; display: inline">
                    </div>

                </div>

            </div>
            <div class="card-footer">
                <small class="text-muted">This page generated by <a href="https://github.com/zfrenchee/Axial" target="_blank">Axial</a></small>
            </div>
        </div>
    </div>

    <div id="graph-container" class="col-md col-12"></div>

</div>


{% endblock %}

{% block scripts %}

{{ scripts_block }}

<script type="text/javascript">

var bar = Bar(names_and_differentials);

Object.keys(names_and_differentials).forEach(name => $("#datasets").append(
    `<div class="form-check">
        <input class="form-check-input" type="checkbox" name="data" value="${name}" id="${name}" checked>
        <label for="${name}">${name}</label>
    </div>`
));

Object.keys(names_and_differentials).forEach((name, i) => $("#sort_by").append(
    `<div class="form-check">
        <input class="form-check-input" type="radio" name="sort_by" value="${name}" id="${name}" ${i === 0 ? 'checked' : ''}>
        <label for="${name}">${name}</label>
    </div>`
));

var single_color = false;
var colors;
reset_color_palette();

/////////////////////////////////////////////////////////////////////////////
                     ///////    Colors   ///////
/////////////////////////////////////////////////////////////////////////////

function reset_color_palette() {

    if (single_color) { colors = ordinal_colors() } else { colors = reds_and_blues(); }

    $("#dataset_colors").empty();
    Object.keys(names_and_differentials).forEach(name => $("#dataset_colors").append(
        `<tr><td><label style="display:block;">${name}</label></td>
        <td><input type="color" value="${colors[name].low}" name="${name}" id="low"></td>
        ${ single_color ? '' : `<td><input type="color" value="${colors[name].high}" name="${name}" id="high"></td>` }
        <tr>`
    ));

    bar.style({'colors_':colors});

    $("input[type='color']").change(function () {

        if (single_color) {
            colors[$(this).attr('name')]['low'] = this.value;
            colors[$(this).attr('name')]['high'] = this.value;
        } else {
            colors[$(this).attr('name')][this.id] = this.value;
        }

        bar.style({'colors_': colors});
     });
}

function ordinal_colors() {

    return _.object(Object.keys(names_and_differentials).map((key, i) => { return [key, {'low': d3.schemeCategory10[i%10], 'high': d3.schemeCategory10[i%10]}]}));
}

function reds_and_blues() {

    return _(names_and_differentials).mapObject(vals => {
        // var blues = [175, 250];
        // var reds = [330, 45];
        var random_h = Math.random();
        var random_s = Math.random();
        var random_l = Math.random();
        return {
            'low':  d3.hsl((random_h * 75 + 175),         random_s * 0.5 + 0.5, random_l * 0.4 + 0.4).hex(),
            'high': d3.hsl(((random_h * 75 + 330) % 360), random_s * 0.5 + 0.5, random_l * 0.4 + 0.4).hex(),
        };
    });
}

/////////////////////////////////////////////////////////////////////////////
                     ///////    Controls   ///////
/////////////////////////////////////////////////////////////////////////////

var chooseGeneSet = document.getElementById("chooseGeneSet");
var chooseGeneSetform = new Awesomplete(chooseGeneSet, {
    list: Object.entries(gene_sets),
    maxItems: 30,
    replace: function (text) { this.input.value = text.label; }
});

var findGeneSet = document.getElementById("findGeneSet");
var findGeneSetform = new Awesomplete(findGeneSet, {
    list: Object.entries(gene_sets),
    maxItems: 1000,
    replace: function (text) { this.input.value = text.label; },
    filter: function (text, input) { return text.value.includes(input) || text.value.includes(input.toUpperCase()); }
});

function complete_selection(e) {
    selected_gene_set_name = e.text.label;
    selected_genes = e.text.value;
    bar.restart({'selected_gene_set_name_':selected_gene_set_name, 'selected_genes_':selected_genes});
    refresh_genes();
    chooseGeneSet.value = selected_gene_set_name; findGeneSet.value = selected_gene_set_name;
};

chooseGeneSet.addEventListener('awesomplete-selectcomplete', complete_selection);
findGeneSet.addEventListener('awesomplete-selectcomplete', complete_selection);


chooseGenes = $('#chooseGenes');
function refresh_genes() { chooseGenes.text(bar.get_sorted_gene_list().join(", ")); }

function manual_gene_list_edit(e) {
    new_list = $(this).text().split(/[\s,;\t\n]+/).filter(n => n);
    if (!array_shallow_equal(new_list, bar.get_sorted_gene_list())) {
        bar.restart({'selected_gene_set_name_':'', 'selected_genes_':new_list});
    }
}
manual_gene_list_edit_debounced = _.debounce(manual_gene_list_edit, 1000)
chooseGenes.on('input', manual_gene_list_edit_debounced);


$("#q_threshold").change(         function () { bar.restart({'q_threshold_': parseFloat(this.value)}) });
$("#fc_threshold").change(        function () { bar.restart({'fc_threshold_': parseFloat(this.value)}) });
$("input[name='data']").change(   function () { bar.restart({'selected_datasets_': $("input[name='data']:checked").map( function () { return $(this).val(); }).get()});});
$("#sort_by input:radio").change( function () { bar.restart({'sort_by_': this.value}); });
$("#single_color").change(        function () { single_color = this.checked; reset_color_palette(); });
$("#show_legends").change(        function () { bar.style({'show_legends_': this.checked}); });

$("#row_thickness").change(        function () { bar.render({'row_thickness_': parseFloat(this.value)}); });
$("#margin_between_bars").change(  function () { bar.render({'margin_between_bars_': parseFloat(this.value)}); });
$("#margin_between_rows").change(  function () { bar.render({'margin_between_rows_': parseFloat(this.value)}); });


/////////////////////////////////////////////////////////////////////////////
                 ///////    Download SVG    ///////
/////////////////////////////////////////////////////////////////////////////

d3.select("#download").on("click", function() {

    d3.select(this)
      .attr("href", 'data:application/octet-stream;base64,' + btoa(unescape(encodeURIComponent(d3.select("#graph-container").html()))))
      .attr("download", "plot.svg")
})

$("#degenes").click(function() { d3.select(this).attr("href", 'data:application/octet-stream;base64,' + btoa(bar.get_sorted_gene_list().join("\n"))).attr("download", "DE_Genes.txt") });

$('#hide-show').click(function(e) { $('.menu').toggleClass('hidden'); });

    </script>


{% endblock %}


