{% extends "tabbed.html" %}

{% block head %}
<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>

<!--To rebuild or modify those links with the latest versions of the included software please visit:-->
<!--https://datatables.net/download/#bs/jq-2.2.4/jszip-3.1.3/pdfmake-0.1.27/dt-1.10.15/b-1.3.1/b-colvis-1.3.1/b-html5-1.3.1/b-print-1.3.1/cr-1.3.3/fc-3.2.2/fh-3.1.2/sc-1.4.2-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/v/bs5/jq-3.7.0/jszip-3.10.1/dt-2.0.2/b-3.0.1/b-colvis-3.0.1/b-html5-3.0.1/b-print-3.0.1/cr-2.0.0/fc-5.0.0/fh-4.0.1/sc-2.4.1/datatables.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/v/bs5/jq-3.7.0/jszip-3.10.1/dt-2.0.2/b-3.0.1/b-colvis-3.0.1/b-html5-3.0.1/b-print-3.0.1/cr-2.0.0/fc-5.0.0/fh-4.0.1/sc-2.4.1/datatables.min.js"></script>
{% endblock %}

{% block tabcontent %}
  <div class="row">
    <div class="col-lg-12" style="margin: 5px">
      <div style="align-items: center; display: flex; margin-top: 5px">
        <span class="header-inline">Downloads:</span>
        <a href="busco_results.csv" target="_blank" rel="noopener noreferrer" class="btn btn-outline-secondary">
          BUSCO results (csv)
        </a>
      </div>
      <p style="margin-top: 10px">
        This file won't necessarily reflect dynamic sorting or filtering
        options based on the interactive table below.
      </p>

      <!-- Column Selection Box -->
      <div class="row mb-3">
        <div class="col-lg-12">
          <div class="card">
            <div class="card-header">
              <h6>Column selection</h6>
              <small class="text-muted">Click on columns to toggle their visibility in the table below.</small>
            </div>
            <div class="card-body">
              <div id="columnSelectionBox" class="sample-selection-container">
                <!-- Column buttons will be populated by JavaScript -->
              </div>
              <hr class="my-3" style="border-color: #dee2e6;">
              <div class="d-flex flex-wrap align-items-center gap-3">
                <button id="selectAllColumnsBtn" class="btn btn-sm btn-outline-primary">Show All</button>
                <button id="selectDefaultColumnsBtn" class="btn btn-sm btn-outline-secondary">Show Default</button>
                <span id="columnCount" class="ms-auto text-muted">0 columns visible</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div style="overflow-x:auto;">
        <table id="table" class="table table-hover table-striped table-bordered"></table>
      </div>
      <div id="loading" class="spinner">
        <div class="rect1"></div>
        <div class="rect2"></div>
        <div class="rect3"></div>
        <div class="rect4"></div>
        <div class="rect5"></div>
      </div>
    </div>
  </div>

  <script id="data" type="application/json">{{ table }}</script>
  <script type="text/javascript">
    $(document).ready(function(){
      adjustTagsToBS3()

      const data = JSON.parse(document.getElementById('data').innerHTML);
      const defaultVisibleColumns = 7;
      let dataTableInstance;

      function updateColumnCount() {
        const visibleCount = dataTableInstance.columns().visible().toArray().filter(v => v).length;
        document.getElementById('columnCount').textContent = `${visibleCount} column${visibleCount !== 1 ? 's' : ''} visible`;
      }

      function toggleColumn(columnIndex) {
        const checkbox = document.querySelector(`[data-column-index="${columnIndex}"]`);
        const column = dataTableInstance.column(columnIndex);
        column.visible(checkbox.checked);
        updateColumnCount();
      }

      function showAllColumns() {
        dataTableInstance.columns().visible(true);
        document.querySelectorAll('.column-checkbox').forEach(checkbox => {
          checkbox.checked = true;
        });
        updateColumnCount();
      }

      function showDefaultColumns() {
        const totalColumns = dataTableInstance.columns()[0].length;
        dataTableInstance.columns().visible(false);

        for (let i = 0; i < Math.min(defaultVisibleColumns, totalColumns); i++) {
          dataTableInstance.column(i).visible(true);
        }

        document.querySelectorAll('.column-checkbox').forEach((checkbox, index) => {
          checkbox.checked = index < defaultVisibleColumns;
        });

        updateColumnCount();
      }

      // Construct initial table header
      var table = $('#table'), head = $('<thead></thead>'), row = $('<tr></tr>');
      table.append(head), head.append(row);
      $.each(data.columns, function(i, val) {
        row.append(function() {
          return '<th>' + val + '<br></th>';
        });
      });

      // Initialize DataTable with column visibility settings
      const columnDefs = data.columns.map((col, index) => ({
        targets: index,
        visible: index < defaultVisibleColumns
      }));

      dataTableInstance = table.DataTable({
        data: data.data,
        fixedHeader: true,
        pageLength: {{ page_size }},
        dom: 'frtip',
        columnDefs: columnDefs,
        autoWidth: false,
        scrollX: true
      });

      // Populate column selection box after DataTable is initialized
      loading.remove();
      console.log('Successfully loaded table!');

      const columnSelectionBox = document.getElementById('columnSelectionBox');
      data.columns.forEach((columnName, index) => {
        const isDefaultVisible = index < defaultVisibleColumns;

        const wrapper = document.createElement('div');
        wrapper.className = 'form-check form-check-inline me-3 mb-2';

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'form-check-input column-checkbox';
        checkbox.id = `col-${index}`;
        checkbox.checked = isDefaultVisible;
        checkbox.dataset.columnIndex = index;
        checkbox.onchange = () => toggleColumn(index);

        const label = document.createElement('label');
        label.className = 'form-check-label';
        label.htmlFor = `col-${index}`;
        label.textContent = columnName;

        wrapper.appendChild(checkbox);
        wrapper.appendChild(label);
        columnSelectionBox.appendChild(wrapper);
      });

      // Add event listeners
      document.getElementById('selectAllColumnsBtn').onclick = showAllColumns;
      document.getElementById('selectDefaultColumnsBtn').onclick = showDefaultColumns;

      updateColumnCount();

      table.on('error.dt', function(error, settings, techNote, message) {
        // From 'js-error-handler.html'
        handleErrors([error, settings, techNote, message], loading, helpMsg);
      });
    });
  </script>
{% endblock %}

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