<%@language = "javascript" %>
<% /*
    $Revision$
    $Id$

    ChatterAccept.asp

    Een Frontoffice medewerker wil wel beschikbaar zijn om te chatten
*/

%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="./chat.inc" -->
<%
FCLTHeader.Requires({plugins:["jQuery"], js: ["jquery-ui.js", "./notify.js", "date.js"]})

var acceptchannelId = shared.random();
var dis_key = getQParamInt("dis_key", -1); // discipline
var ins_discipline_omschrijving = get_disc_name(dis_key);

Application.Lock();
var chat_queue = JSON.parse(Application(chat_queue_name) || "{}");

if (!chat_queue.accepting)
    chat_queue.accepting = {};

for (var ch in chat_queue.accepting)
{   // Verwijder achtergebleven channels van deze gebruiker.
    if (chat_queue.accepting[ch].prs_key == user_key)
        delete chat_queue.accepting[ch];
}
chat_queue.accepting[acceptchannelId] = { prs_key: user_key, since: new Date() };

Application(chat_queue_name) = JSON.stringify(chat_queue);
Application.UnLock();
%>
<html>
<head>
<%
   FCLTHeader.Generate();
%>
<script>
    FcltMgr.startEdit(window); // maakt hem hot
    var acceptchannelId = "<%=acceptchannelId%>";
    var dis_key = <%=dis_key%>;

    function accept_chat()
    {
        var wantId = $(this).data("wantid");
        var prs_key = $(this).data("prs_key");
        var message = $(this).data("message");
        var naam = $(this).data("prs_naam");
        FcltMgr.openDetail( "appl/chat/Chatter.asp?chatsendid=" + wantId + "&prs_key=" + prs_key + "&message=" + escape(message) + "&accept=1&naam=" + naam, L("lcl_chatter_incoming").format(naam));
        view_queue(); // op de achtergrond blijven refreshen
    }

    async function show_queue(data)
    {
        //$("#chatqueue").html("<xmp>" + JSON.stringify(data, null, 4) + "</xmp>");
        var old_height = $("#chatqueue").height();
        var ts = $("#chatqueue").data("ts");
        var html_queue = $("<table class='rstable sortable'>");
        html_queue.append("<tr>"
                           +  "<th>"+L('lcl_chat_name')+"</th>"
                           +  "<%=(dis_key < 0 ? "<th>"+L('cht_discipline')+"</th>" : "")%>"
                           +  "<th>"+L('lcl_chat_since')+"</th>"
                           +  "<th>"+L('lcl_chat_message')+"</th>"
                           +  "<th>"+L('lcl_chat_status')+"</th>"
                           +  "</tr>");

        var ago60s = new Date();
        ago60s.setSeconds(ago60s.getSeconds() - 60);
        var alert_new = "";
        var notify_args = [];
        for (var wantId in data.chat_queue.wanting)
        {
            var wanting = data.chat_queue.wanting[wantId];
            var stripped_message = "";
            await $.post("../Shared/get_shared_info.asp", {
                req_info: "strip_bb_code",
                input: wanting.message
            }, function (json) {
                stripped_message = json.stripped_input;
            }).promise();

            if (ts && wanting.since > ts) {
                alert_new += "\n" + I("fa-angle-right") + " " + safe.html(wanting.naam);
                if (notify_args.length) { // Meerdere, dan anoniem
                    notify_args = [L("lcl_chat_new"), {
                        body: L("lcl_chats_new"),
                        icon: "<%=rooturl%>/appl/pictures/avatarx.jpg"
                    }]
                } else {
                    notify_args = [wanting.naam, {
                        body: L("lcl_chat_new"),
                        icon: wanting.picture,
                        // data: wantId
                    }];
                }
            }
            var statustxt = "";
            var alivedate = new Date(wanting.alive || wanting.since);
            if (alivedate < ago60s)
                var statustxt = L("lcl_chat_status_idle").format(toTimeString(alivedate, true));
            else if (new Date(wanting.since) < ago60s)
                var statustxt = L("lcl_chat_status_waiting").format(Math.round((new Date() - wanting.since)/1000));
            var html_row = $("<tr>").append($("<td>").text(wanting.naam))
                                    <%=(dis_key < 0 ? '.append($("<td>").text(wanting.dis_oms || ""))' : '')%>
                                    .append($("<td>").text(toTimeString(new Date(wanting.since), true)))
                                    .append($("<td>").text(stripped_message))
                                    .append($("<td>").text(statustxt))
                                    .data("message", wanting.message)
                                    .data("wantid", wantId)
                                    .data("prs_key", wanting.prs_key)
                                    .data("prs_naam", wanting.naam)
                                    .attr("title", "<%=L('lcl_chat_accept_action')%>")
                                    .click(accept_chat);
            html_queue.append(html_row);
        }
        if (notify_args.length) {
            await Notification.requestPermission().then(result => {
                if (result === "granted") {
                    let notification = new Notification(...notify_args);
                    notification.onclick = _ => {
                        window.parent.$("a[href='#" + window.name + "']").click(); // Activeer mijn tabje
                    };
                } else if (alert_new) { // Altijd true als we hier komen
                    FcltMgr.alert(L("lcl_chat_incoming").format(alert_new), { ishtmlsafe: true, title: L("lcl_chat_new") });
                }
            });
        }

        $("#chatqueue").data("ts", (new Date(data.since)).getTime())
                       .html(html_queue);
        if (old_height != $("#chatqueue").height())
            FcltMgr.resized();
        notify.wait(window.acceptchannelId, null, view_queue, { alwaysafter: 10 });
    }

    function onCloseHot()
    {
        var data = { channelId: "<%=acceptchannelId%>" };
        <% protectRequest.dataToken("data"); %>
        jQuery.ajaxSetup({async: false}); // Anders faalt o.a. bij IE9 de $.post bij afsluiten
        $.post( "ChatClose.asp"
              , data
              , FcltCallback
              , "json"
              );
    }

    function view_queue()
    {
        $.getJSON( "./ChatQueueGet.asp" + (dis_key > 0 ? "?dis_key=" + dis_key : ""), show_queue);
        return true;
    }
    $(view_queue);
</script>
</head>
<body>
<div id="chatqueue"></div>
</body>
</html>
<% ASPPAGE_END(); %>
