{% extends 'tabbed.html' %}

{% block head %}
<title>Embedding Vega-Lite</title>
<script src="js/bootstrapMagic.js" type="text/javascript"></script>
<link href="css/styles.css" rel="stylesheet"/>
<script type="text/javascript">
    // temporary hack to make it look good with Bootstrap 5
    removeBS3refs();
</script>
<script src="https://cdn.jsdelivr.net/npm//vega@5" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm//vega-lite@5.16.3" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm//vega-embed@6" type="text/javascript"></script>
<link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha256-YvdLHPgkqJ8DVUxjjnGVlMMJtNimJ6dYkowFFvp4kKs=" rel="stylesheet"/>
{% endblock %}

{% block tabcontent %}
<script crossorigin="anonymous" integrity="sha256-9SEPo+fwJFpMUet/KACSwO+Z/dKMReF9q4zFhU/fT9M=" src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<br>
<div class="row" style="justify-content: space-evenly; align-items: start;">
    <div class="row" style="margin-bottom: 10px">
        <div class="col-lg-12" style="margin: unset">
            <div class="card">
                <h5 class="card-header">BUSCO summary statistics</h5>
                <div class="card-body">
                    <p>
                        The table below shows the summary statistics of the BUSCO marker count
                        fractions for the categories
                        <b>Single</b>, <b>Duplicated</b>, <b>Fragmented</b>, <b>Missing</b> 
                        {% if not comp_cont %}and {% else %}, {% endif %}<b>Complete</b>{% if comp_cont %}, <b>Completeness</b> {% if not unbinned %}and <b>Contamination</b>.{% else %}, <b>Contamination</b>
                        and <b>Unbinned contigs</b>.{% endif %}{% endif %} The statistics are calculated for the categories across <b>all MAGs</b> in <b>all samples</b>{% if unbinned %}, including the
                        percentage of <b>Unbinned contigs</b> per sample{% endif %}.
                    </p>
                    <table id="summaryTable" class="table table-hover">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">% single</th>
                            <th scope="col">% duplicated</th>
                            <th scope="col">% fragmented</th>
                            <th scope="col">% missing</th>
                            <th scope="col">% complete</th>
                            {% if comp_cont %}
                                <th scope="col">% completeness</th>
                                <th scope="col">% contamination</th>
                            {% endif %}
                            {% if unbinned %}
                                <th scope="col">% unbinned contigs</th>
                            {% endif %}
                        </tr>
                    </thead>
                    <tbody>
                        <tr id="rowMinimum">
                          <th scope="row">Minimum</th>
                        </tr>
                        <tr id="rowMedian">
                          <th scope="row">Median</th>
                        </tr>
                        <tr id="rowMean">
                          <th scope="row">Mean</th>
                        </tr>
                        <tr id="rowMaximum">
                          <th scope="row">Maximum</th>
                        </tr>
                        <tr id="rowTotal">
                          <th scope="row">Total count</th>
                        </tr>
                    </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="row" style="margin-bottom: 10px">
        <div class="col-lg-12">
            <div class="card">
                <h5 class="card-header">Distribution of BUSCO marker gene counts</h5>
                <div class="card-body">
                    <p>
                        The histograms in the first row below show distributions of BUSCO marker
                        count fractions across all MAGs in all samples for all the marker categories,
                        as represented in the table above.

                        The histograms in the second row show the distributions of assembly metrics
                        gathered for each MAG across all the samples and can be used to evaulate the
                        assembly quality of the MAGs.
                    </p>
                    <div class="col-lg-12" id="summaryHistogramsMarkers">
                        <div id="plotMarkers" style="margin-top: 5px"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row" style="margin-bottom: 10px">
        <div class="col-lg-12">
            <div class="card">
                <h5 class="card-header">Histogram per sample</h5>
                <div class="card-body" style="display: flex; align-items: center">
                    <div class="col-lg-3" style="margin-right: 20px">
                        <p>
                            The histogram shows the distribution of the selected BUSCO marker
                            count fractions for the selected sample. You can use the dropdown
                            to select the metric and the search box to type the name of
                            the sample you want to see on the plot. You can use this visualization
                            to evaluate the quality of MAGs in a specific sample and compare
                            it to the overall distribution shown in the plots above.
                        </p>
                    </div>
                    <div class="col-lg-9" style="display: flex; align-items: center; justify-content: space-evenly">
                        <div class="col-lg-5" id="selectableHistogramControls"></div>
                        <div class="col-lg-4" id="selectableHistogram">
                            <div id="plotSelectable" style="margin-top: 5px"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% if comp_cont %}
    <div class="row" style="margin-bottom: 10px">
        <div class="col-lg-12">
            <div class="card">
                <h5 class="card-header">Completeness vs Contamination</h5>
                <div class="card-body">
                    <p>
                        This scatterplot shows the relationship between BUSCO completeness and contamination
                        for each MAG across your dataset. Each point is colored by sample ID.
                    </p>
                    <div class="col-lg-12" id="scatterDropdownControls" style="margin-bottom: 10px;"></div>
                    <div id="scatterPlotDiv" style="margin-top: 10px;"></div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    {% if unbinned %}
    <div class="row" style="margin-bottom: 10px">
        <div class="col-lg-12">
            <div class="card">
                <h5 class="card-header">Distribution of unbinned contigs</h5>
                <div class="card-body" style="display: flex; align-items: center">
                    <div class="col-lg-3" style="margin-right: 20px">
                        <p>
                            The histogram shows the distribution of unbinned contig metrics
                            across all samples. You can use the radio buttons to switch between
                            displaying the absolute count or the percentage of unbinned contigs.
                            This visualization provides insight into the overall distribution 
                            and variability of unbinned sequences, enabling the identification of 
                            patterns or anomalies in contig binning efficiency across samples.
                        </p>
                    </div>
                    <div class="col-lg-9" style="display: flex; align-items: center; justify-content: space-evenly">
                        <div class="col-lg-5" id="selectableHistogramUnbinnedControls"></div>
                        <div class="col-lg-4" id="selectableUnbinnedHistogram">
                            <div id="plotUnbinned" style="margin-top: 5px"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<script id="vega_summary_json" type="application/json">
    {{
        vega_summary_json
        |
        safe
    }}
</script>

<script id="vega_summary_selectable_json" type="application/json">
    {{
        vega_summary_selectable_json
        |
        safe
    }}
</script>
<script id="vega_selectable_unbinned_json" type="application/json">
    {{
        vega_selectable_unbinned_json
        |
        safe
    }}
</script>

<script id="summary_stats_json" type="application/json">
    {{
        summary_stats_json
        |
        safe
    }}
</script>

<script id="scatter_json" type="application/json">
    {{ scatter_json | safe }}
</script>

<script type="text/javascript">
    $(document).ready(function () {
        // temporary hack to make it look good with Bootstrap 5
        adjustTagsToBS3()

        const summarySpec = JSON.parse(document.getElementById('summary_stats_json').textContent);
        console.log(summarySpec)

        const rows = ['rowMinimum', 'rowMedian', 'rowMean', 'rowMaximum', 'rowTotal'];
        const indices = ['min', 'median', 'mean', 'max', 'count'];
        const cols = ['single', 'duplicated', 'fragmented', 'missing', 'complete', 'completeness', 'contamination', 'unbinned_contigs'];
        rows.forEach((rowId, index) => {
            let rowElement = document.getElementById(rowId)
            let colVals = summarySpec.data[index]
            console.log(colVals)
            cols.forEach((col) => {
                let td = document.createElement('td');
                td.textContent = colVals[col];
                rowElement.appendChild(td);
            })
        })

        const vegaSpecSummary = JSON.parse(document.getElementById('vega_summary_json').textContent);
        vegaEmbed("#plotMarkers", vegaSpecSummary).then(
            function (result) {
                result.view.logLevel(vega.Warn);
                window.v = result.view;
            }
        ).catch(
            function (error) {
                handleErrors([error], $("#plotMarkers"));
            }
        );

        const vegaSpecSelectable = JSON.parse(document.getElementById('vega_summary_selectable_json').textContent);
        vegaEmbed("#plotSelectable", vegaSpecSelectable).then(
            function (result) {
                result.view.logLevel(vega.Warn);
                window.v = result.view;
            }
        ).catch(
            function (error) {
                handleErrors([error], $("#plotSelectable"));
            }
        ).then(
            function(result) {
                let plotSelectable = document.getElementById('plotSelectable')
                let chartWrapper = plotSelectable.getElementsByClassName('chart-wrapper')
                let vegaBindings = chartWrapper[0].getElementsByClassName('vega-bindings')

                let dropdown = vegaBindings[0].querySelector("select[name=select_metric_category]")
                dropdown.classList.add("btn-sm", "btn-outline", "dropdown-toggle")
                let dropdownLabel = vegaBindings[0].getElementsByClassName("vega-bind-name")[0]
                dropdownLabel.innerHTML = "Select metric:"

                let searchBox = vegaBindings[0][1]
                searchBox.classList.add("form-control-sm")
                let searchBoxLabel = vegaBindings[0].getElementsByClassName("vega-bind-name")[1]
                searchBoxLabel.innerHTML = "Find sample:"

                let plotSelectableControls = document.getElementById('selectableHistogramControls')
                plotSelectableControls.appendChild(vegaBindings[0])
            }
        );
        const scatterSpec = JSON.parse(document.getElementById('scatter_json').textContent);
        vegaEmbed("#scatterPlotDiv", scatterSpec).then(
            function (result) {
                result.view.logLevel(vega.Warn);

        const dropdownWrapper = document.querySelector("#scatterPlotDiv .vega-bindings");
        const target = document.getElementById('scatterDropdownControls');
        if (dropdownWrapper && target) {
            target.appendChild(dropdownWrapper);
        }
        }
        ).catch(
            function (error) {
                handleErrors([error], $("#scatterPlotDiv"));
            }
        );
        const vegaSpecSelectableUnbinned = JSON.parse(document.getElementById('vega_selectable_unbinned_json').textContent);
        vegaEmbed("#plotUnbinned", vegaSpecSelectableUnbinned).then(
            function (result) {
                result.view.logLevel(vega.Warn);
                window.v = result.view;
            }
        ).catch(
            function (error) {
                handleErrors([error], $("#plotUnbinned"));
            }
        ).then(
            function(result) {
                let plotUnbinned = document.getElementById('plotUnbinned')
                let chartWrapper = plotUnbinned.getElementsByClassName('chart-wrapper')
                let vegaBindings = chartWrapper[0].getElementsByClassName('vega-bindings')

                let dropdown = vegaBindings[0].querySelector("select[name=select_metric_category]")
                dropdown.classList.add("btn-sm", "btn-outline", "dropdown-toggle")
                let dropdownLabel = vegaBindings[0].getElementsByClassName("vega-bind-name")[0]
                dropdownLabel.innerHTML = "Select metric:"

                let plotUnbinnedControls  = document.getElementById('selectableHistogramUnbinnedControls')
                plotUnbinnedControls.appendChild(vegaBindings[0])
            }
        );
    });
</script>

{% endblock %}

{% block footer %}
{% set loading_selector = '#loading' %}
{% include 'js-error-handler.html' %}
{% endblock %}
