{% extends 'base.jinja' %}
{% block report_data %}
<div class="container clearfix">
    <div class="people-list" id="people-list">
      <ul class="list" id="list">

      </ul>
    </div>
    <div class="chat">
      <div class="chat-header clearfix">
        <div class="chat-about">
          <div class="chat-with" id="chat-with">Click on the left to view messages</div>
          <div class="chat-num-messages" id="chat-num-messages"></div>
        </div>
        </div> <!-- end chat-header -->
        <div id="chat-history" class="chat-history">
        </div>
    </div>
</div>
<br />
<br />
{% endblock %}
{% block script_block_end %}
<script>
function createDivMessages (m){

    var messType = '<div class="message my-message">';
    var liTag = '<li>';
    var messDataTag = '<div class="message-data">';
    var name = m["data-name"];

    if (m["from_me"] == 1) {
        messType = '<div class="message other-message float-right">';
        liTag = '<li class="clearfix">'
        messDataTag = '<div class="message-data align-right">';
        name = "Me";
    }

    var res = liTag;
    res += messDataTag;
    res += '<span class="message-data-time" >';
    res += m["data-time"];
    res += '</span> &nbsp; &nbsp;';
    res += '<span class="message-data-name" >';
    res += name;
    res += '</span>';
    res += '</div>';
    res += messType;
    res += m["body_to_render"];
    res += '</div>';
    res += '</li>';

    return res;
}

function showHistory (messages, name){

    html = "<ul>";
    for (let m in messages){
      html += createDivMessages(messages[m], name);
    }
    html += "</ul>";
    $("#chat-history").html(html);
    return false;
}

function createPeopleList(list){

    var res = '';
    for (let p in list){
        res += '<li class="clearfix" id="';
        res += list[p];
        res += '">';
        res +=  '<div class="about">';
        res +=    '<div class="name">';
        res += list[p];
        res += '</div>';
        res +=  '</div>';
        res += '</li>';
    }
    $("#list").html(res);
}

function updateHeader(name, num){
    $("#chat-with").html(name);
    $("#chat-num-messages").html("Total: "+num)
    return false;
}

$(document).ready(function() {
    var messages = JSON.parse(json);

    createPeopleList(Object.keys(messages));

    $('.people-list li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
        var id = $(this).attr('id');
        showHistory(messages[id]);
        updateHeader(id,Object.keys(messages[id]).length);
        return false;
    });
});
</script>
{% endblock %}