{% extends "otree/admin/Session.html" %}
{% block internal_scripts %}
{{ block.super }}
<script>
$(document).ready(
    function() {
        ajax_json_participants();
        setInterval(ajax_json_participants , 4000);
        ajax_advance();
    }
);
// wrap timestamp into timeago tag
function wrap_timestamp() {
    $( "td[data-field='_last_page_timestamp']:not(:has(*))" ).each(function( index ) {
        if ( $(this).text() != "") {
            var date = new Date($(this).text() * 1000);
            $(this).text("");
            $(this).append('<abbr class="timeago" title="{0}">Last submit was done that long ago</abbr>'.format(date.toISOString()));
            $("abbr.timeago").timeago();
        }
    });
    // remove timestamp for disconnected users
    $( "tr:has(> td[data-field='status']:contains('Disconnected'))" ).each(function( index ) {
        $(this).children("td[data-field='_last_page_timestamp']").text("");
    });
}
// ajax request for advance session button
function ajax_advance() {
    $('#advance_users').on('click', function () {
        $('#advance_users').attr("disabled", true);
        $.ajax({
            url: '{% url 'session_advance' session.pk %}',
            type: 'GET',
            error: function(jqXHR, textStatus) {
                $( "div#server_error" ).show();
            },
            success: function() {
                $( "div#server_error" ).hide();
                ajax_json_participants();
                $('#advance_users').attr("disabled", false);
            }
        });
    });
}
// ajax requests to the server for participants data
function ajax_json_participants() {
    $.ajax({
        url: '{% url "session_participants_list" session.code %}',
        type: 'GET',
        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 htmlTable = ConvertJsonToTable(new_json,
                    "monitor_table",
                    "table table-bordered table-hover table-condensed");
                $("#div-table").append(htmlTable);
            }
            // compute delta and update
            // corresponding values in table 
            else {
                var diffpatcher = jsondiffpatch.create({
                    objectHash: function(obj) {
                        return obj.code;
                    }
                });
                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
                        );
                    }
                }
            }
            wrap_timestamp();
            $( "table" ).data("raw", new_json);
        }
    });
}
</script>
{% endblock %}
{% block content %}
{{ block.super }}
<div id="div-table">
</div>
<br/>
<a id="advance_users" class="btn btn-primary" role="button" data-toggle="popover" data-trigger="hover"
data-content="By clicking this button the slowest user(s)
will be automatically advanced by one page, while the other users
will remain where they are (unless perhaps if they have a waiting page).">
Advance slowest user(s)
</a>
<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 %}
