{% extends "otree/admin/Session.html" %}
{% block internal_scripts %}
{{ block.super }}
<script>
$(document).ready(
    function() {
        ajax_json_results();
        setInterval(ajax_json_results , 2000);
    }
);
function ajax_json_results() {
    $.ajax({
        url: '{% url "session_results" session.code %}',
        type: 'GET',
        contentType: "application/json",
        error: function(jqXHR, textStatus) {
            $( "div#server_error" ).show();
        },
        success: function (new_json) {
            $( "div#server_error" ).hide();
            var old_json = $( "table" ).data("raw");
            // build table for the first time
            if ( old_json === undefined ) {
                var tableBody = ConvertJsonToTable(new_json,
                    "",
                    "",
                    "",
                    true);
                $( "thead" ).after(tableBody);
            }
            // compute delta and update
            // corresponding values in table 
            else {
                var diffpatcher = jsondiffpatch.create({
                    objectHash: function(obj) {
                        return obj.participant_label;
                    }
                });
                var delta = diffpatcher.diff(old_json, new_json);
                for (i in delta) {
                    for (header_name in delta[i]) {
                        var cell_to_update = $( "tbody tr:eq(" + i + ") \
                                                 td[data-field='" + header_name + "']" );
                        cell_to_update.text(delta[i][header_name][1]);
                        cell_to_update.css('background-color', 'green');
                        cell_to_update.animate({
                                backgroundColor: "white"
                            },
                            5000
                        );
                    }
                }
            }
            $( "table" ).data("raw", new_json);
        }
    });
}
</script>
{% endblock %}

{% block content %}
{{ block.super }}
<div style="overflow: auto">
<table class="header-fixed table table-bordered table-hover table-condensed">
    <thead>
        <tr>
            <th rowspan="3" class="text-center">Player label</th>
            {% for header, colspan in subsession_headers %}
                <th colspan="{{ colspan }}">{{ header }}</th>
            {% endfor %}
        </tr>
            {% for header, colspan in model_headers %}
                <th colspan="{{ colspan }}">{{ header }}</th>
            {% endfor %}
        </tr>
        <tr>
            {% for header in field_headers %}
                <th>{{ header }}</th>
            {% endfor %}
        </tr>
    </thead>
</table>
</div>
<div id="server_error" class="alert alert-danger" style="display: none;"> 
    <a href="#" class="close" data-dismiss="alert">&times;</a>
    "Failed to connect to server"
</div>
{% endblock %}
