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

     notify.asp

     Standalone notify mechanisme
     Doel is vooral om het zéér lichtgewicht te maken omdat het potentieel
     door heel veel mensen elke x seconde wordt aangeroepen

     Vooralsnog doen we niet aan payloads

     LET OP:
     We includen common.inc (en daarmee m_connections.inc) niet
     Daarmee hebben we dus geen database toegang (/nodig)!!!
*/

var JSON_Result = true;

%>
<!-- #include file="../Shared/json2.js" -->
<!-- #include file="../Shared/logger.inc" -->
<!-- #include file="../Shared/shared.inc" -->
<%
Response.ContentType = "application/json";

Response.AddHeader("Access-Control-Allow-Origin", "*");

var channelId = getQParam("channelId");
var action = getQParam("action"); // check, signal

var result = { ts: new Date().getTime() };

Application.Lock();
var notifydata = JSON.parse(Application("notifydata") || "{}");
if (action == "check")
{
    // determine last time a message was send from this channel (last alive)
    // or inactive (=1) or terminated (=2)
    if (notifydata.alive && notifydata.alive[channelId])
    {
        if (notifydata.alive[channelId] == 1 || notifydata.alive[channelId] == 2)
        {
            result.end = notifydata.alive[channelId];
        }
        else
        {
            var sendchannelId = getQParam("sendchannelId", "");
            var sendlastalive = notifydata.alive[sendchannelId];
            // determine datetime of latest communication
            result.last_alive = (sendchannelId && sendlastalive ? Math.max(notifydata.alive[channelId], sendlastalive) : notifydata.alive[channelId]);
        }
    }

    result.message = notifydata[channelId];
    if (!result.message)
    {
        Response.Write(JSON.stringify(result));
        Response.End(); // Zéér snel klaar.
    }
    // else markering wissen en verderop herschrijven
    delete notifydata[channelId];
}
else if (action == "signal") // action = "signal"
{
    var msg = getQParam("msg", "X");
    notifydata[channelId] = msg; // signal message
    notifydata.alive = notifydata.alive || {};
    if (msg != "X")
    {
        notifydata.alive[msg] = new Date().getTime();
    }
}
else if (action == "end") // end of chat
{
    var msg = getQParam("msg", "1");
    if (channelId in notifydata.alive)
        notifydata.alive[channelId] = msg;
    delete notifydata.alive[getQParam("fromchannelId")]
}

Application("notifydata") = JSON.stringify(notifydata);
Application.UnLock();

Response.Write(JSON.stringify(result));
%>
<% // ASPPAGE_END();
%>
