{% extends "layout.jinja2" %}

{% macro make_table(object_type) %}
    <form id="properties_form_{{ object_type }}" class="autorestore">
        <p><span id="update-marker-{{ object_type }}"></span>Page
            <select name="page" id="page-{{ object_type }}">
                <option value="1" selected>1</option>
            </select> of <span id="num-pages-{{ object_type }}">1</span>.
            Total <span id="num-objects-{{ object_type }}">...</span>;
            maximum
            <select name="per_page" id="per-page-{{ object_type }}">
                {% for perpage in [10,20,50,100,200] %}
                    <option value="{{ perpage }}" {%  if perpage == 50 %}selected{% endif %}>{{ perpage }}</option>
                {% endfor %}
            </select>
            per page.</p>
        <table class="data-table" id="table-{{ object_type }}">
            <tr id="header-row-{{ object_type }}">
                <th id="header-number-{{ object_type }}">Number</th>
                <th class="editable" id="header-colid-1-{{ object_type }}"></th>
                <th id="header-go-{{ object_type }}">Go &rarr;</th>
            </tr>
            <tr>
                <th></th>
                <th id="plotctl-colid-1-{{ object_type }}"></th>
                <th></th>
            </tr>


        </table>
    </form>
{% endmacro %}

{% block content %}
    <script type="text/javascript" src="{{ request.static_url('tangos.web:static/timestepdata.js') }}"></script>

    <h1>Timestep: {{ timestep }}</h1>

    <table id="objects-container"><tr>

    {% for this_object in objects %}
        {%  if this_object['n_items']>0 %}
        <td>
            <h2>{{ this_object['title'] }}</h2>

            {{ make_table(this_object['typetag']) }}
        </td>
        {% endif %}
    {% endfor %}

    </tr></table>



<script>


$.fn.markAsColumnInsertPoint = function(editable_tag) {
    if(this.length===0)
        return;
    $(this).closest('form').on('change', function() {
        updateTableDisplay(editable_tag);
    });
    return $(this).makeEditableTemplate(addBlankColumn, removeColumn, updateColumnData, editable_tag);

}



function updateColumnData(miniLanguageQuery, columnId, editable_tag) {

    $('#header-'+columnId).data('miniLanguageQuery', miniLanguageQuery);

    if(window.dataTables[editable_tag][miniLanguageQuery]!==undefined) {
        data = window.dataTables[editable_tag][miniLanguageQuery]
        if (data===undefined || data.error) {
            $('#header-' + columnId).html("<span class='load_table_failed'>" + miniLanguageQuery + " (failed)</span>")
        } else {
            $('#header-' + columnId).html(miniLanguageQuery);
            updatePlotControlElements('#plotctl-' + columnId, miniLanguageQuery, false, data.can_use_as_filter, false, true);
        }
    } else {
        $('#header-'+columnId).html("<div class='progress-spinner'></div>"+miniLanguageQuery);
        updatePlotControlElements('#plotctl-' + columnId, miniLanguageQuery, false, false, false);
        requestColumnData(editable_tag, miniLanguageQuery, function() {
            updateColumnData(miniLanguageQuery, columnId, editable_tag);
        });
    }
    updateTableDisplay(editable_tag);
}

function addBlankColumn(after, object_tag) {
    var new_name = "column-"+Math.random().toString(36).substring(7);
    $('.data-table tr').each(function(index) {
        $(this).find("#header-"+after).after("<th id='header-"+new_name+"' class='editable'></th>");
        $(this).find("#plotctl-"+after).after("<th id='plotctl-"+new_name+"'></th>");
    })
    $('#header-'+new_name).markAsColumnInsertPoint(object_tag);
    updateTableDisplay(object_tag);
    return new_name;
}

function removeColumn(name, object_tag) {
     $('.data-table tr').each(function(index) {
        $(this).find("#header-"+name).remove();
        $(this).find("#plotctl-"+name).remove();
    })
    updateTableDisplay(object_tag);
}


function setupDynamicTables() {

    setupTimestepTables('{{ timestep_url }}');

    {% for this_object in objects %}
        if(window.dataTables['{{ this_object['typetag'] }}']===undefined) {
            window.dataTables['{{ this_object['typetag'] }}'] = {};
        }

        $('#header-number-{{ this_object['typetag'] }}').data('miniLanguageQuery', "halo_number()");
        $('#header-go-{{ this_object['typetag'] }}').data('miniLanguageQuery', "*go_link");
        $('#header-colid-1-{{ this_object["typetag"] }}').markAsColumnInsertPoint('{{ this_object["typetag"] }}');
        updateTableDisplay('{{ this_object['typetag']  }}');
        requestColumnData('{{ this_object["typetag"] }}', "halo_number()", function() {
            let tables = window.dataTables['{{ this_object["typetag"]  }}'];
            let numbers = tables['halo_number()'].data_formatted;
            let links = new Array(numbers.length);
            for(i=0; i<numbers.length; i++) {
                links[i] = `<a href="{{ this_object["object_url"] }}${numbers[i]}">Go &rarr;</a>`
            }
            tables['*go_link'] = Object();
            tables['*go_link'].data_formatted = links;
            updateTableDisplay('{{ this_object['typetag']  }}');
        })
    {% endfor %}

}



function updateTableDisplay(object_tag) {
    let dataColumns = [];
    $("tr#header-row-"+object_tag+" th").each(function() {
       var miniLanguageQ = $(this).data('miniLanguageQuery');
       if(window.dataTables[object_tag][miniLanguageQ]!==undefined) {
           dataColumns.push(window.dataTables[object_tag][miniLanguageQ].data_formatted);
       } else {
           dataColumns.push(undefined);
       }
    });

    let nData = 0;
    $.each(dataColumns, function(i,c) {
        if(c !== undefined && c.length>nData) {
            nData=c.length;
        }
    });


    $("#table-"+object_tag+" tr.tangos-data").remove();

    let filterArray = getFilterArray(object_tag);

    let rowsPerPage = parseInt($("#per-page-"+object_tag+" option:selected").text());
    let page = parseInt($("#page-"+object_tag+" option:selected").text());
    if (isNaN(page)) page=1;
    let startRow = (page-1)*rowsPerPage;
    let endRow = startRow+rowsPerPage;

    let nRowsTotal=0;
    let displayRows = [];

    for(var i=0; i<nData; i++) {
        let shouldDisplay = true;

        if(filterArray!==undefined)
            shouldDisplay = filterArray[i];

        if(shouldDisplay) {
            if (nRowsTotal<endRow && nRowsTotal>=startRow) {
                display = "<tr class='tangos-data'>"
                $.each(dataColumns, function(j,c) {
                    if(c!==undefined)
                        display+="<td>"+c[i]+"</td>";
                    else
                        display+="<td></td>";
                });
                display +="</tr>";
                displayRows.push(display);
            }

            nRowsTotal++;
        }
    }


    var numPages = Math.ceil(nRowsTotal/rowsPerPage);
    $("#num-pages-"+object_tag).text(numPages);
    $("#num-objects-"+object_tag).text(nRowsTotal);

    var pageSelector = $("#page-"+object_tag)
    pageSelector.find("option").remove();
    for(var i=1; i<numPages+1; i++) {
        selected = (i==page)?" selected":"";
        pageSelector.append("<option name='"+i+"'"+selected+">"+i+"</option>")
    }

    $("#table-"+object_tag).append(displayRows);




}


setupDynamicTables();


</script>

{% endblock content %}
