﻿// =========================================================================
// INITIALISE CLASS
// =========================================================================
if (typeof(window.Chat) == "undefined")
    window.Chat = new Object();

// =========================================================================
// INTERNAL VALUES
// =========================================================================
Chat.Debug = false;

Chat.ActionType =
{
    RequestConnection : 0,
    GetTextCount : 1,
    GetText : 2,
    PushText : 3,
    Terminate : 4,
    GetAwaitAuthList : 5,
    RegisterForUpdates :  6
}

Chat.ErrorCode =
{
    None : 0,
    TimeLimit : 1,
    InvalidInput : 2,
    InvalidId : 3,
    AwaitingAuth : 4
}

// =========================================================================
// TRY TO OBTAIN A NEW CHAT CONNECTION
// Callback Parameters:
//  Success  Boolean
//  Id       Guid
//  Message  String
// =========================================================================
Chat.RequestConnection = function(fncCallback)
{
    // Ensure callback method specified
    if (!ObjectDetection.IsFunction(fncCallback))
    {
        if (Chat.Debug)
            alert("Chat.RequestConnection: Invalid fncCallback");
        return;
    }
    
    // Make server call
    var arrParameters = new Array();
    arrParameters[0] = new Chat_DataRetrievals.DataRequestParameter("Action", Chat.ActionType.RequestConnection);
    Chat_DataRetrievals.DataRequest("Chat.RequestConnection", arrParameters, CallbackWrapper, 3);
    
    // Prepare callback
    function CallbackWrapper(bSuccessServerCall, intErrorCode, strId, strInfo, intRetVal)
    {
        // If communication with server failed, return failure with error message
        if (!bSuccessServerCall)
        {
            fncCallback(false, null, strInfo);
            return;
        }
        
        // If server call succeeded, but otherwise request denied, return
        // appropriate info
        if (intErrorCode == Chat.ErrorCode.TimeLimit)
        {
            // Get here if too many attempts are made from same IP
            var strMsg = "We regret to inform you that your IP Address is currently being denied access to this service."
            fncCallback(false, null, strMsg);
            return;
        }
        if (intErrorCode != Chat.ErrorCode.None)
        {
            // Shouldn't get here, but just in case
            var strMsg = "We regret to inform you that your IP Address is currently being denied access to this service."
            fncCallback(false, null, strMsg);
            return;
        }
        
        // If here, then request succeeded
        fncCallback(true, strId, null);
    }
}

// =========================================================================
// TEST WHETHER A CONNECTION IS VALID / AUTHORISED
// Callback Parameters:
//  Success     Boolean
//  Valid       Guid
//  Authorised  String
// =========================================================================
Chat.TestConnectionValid = function(strId, fncCallback)
{
    // Ensure Id string specified
    if (!ObjectDetection.IsString(strId))
    {
        if (Chat.Debug)
            alert("Chat.TestConnectionValid: Invalid strId");
        return;
    }
    // Ensure callback method specified
    if (!ObjectDetection.IsFunction(fncCallback))
    {
        if (Chat.Debug)
            alert("Chat.TestConnectionValid: Invalid fncCallback");
        return;
    }
    
    // Make server call
    // - Use the GetTextCount request type as it will return
    //   ErrorCode.None, .InvalidId or .TimeLimit which will
    //   tell us everything we want to know
    var arrParameters = new Array();
    arrParameters[0] = new Chat_DataRetrievals.DataRequestParameter("Action", Chat.ActionType.GetTextCount);
    arrParameters[1] = new Chat_DataRetrievals.DataRequestParameter("Id", strId);
    Chat_DataRetrievals.DataRequest("Chat.TestConnectionValid", arrParameters, CallbackWrapper, 3);
    
    // Prepare callback
    function CallbackWrapper(bSuccessServerCall, intErrorCode, strId, strInfo, intRetVal)
    {
        // If successfully contact server..
        if (bSuccessServerCall)
        {
            // ..and Connection Id invalid, return this state
            if (intErrorCode == Chat.ErrorCode.InvalidId)
            {
                fncCallback(true, false, null);
                return;
            }
            // ..and Connection Id valid but awaiting authorisation,
            // return this state
            else if (intErrorCode == Chat.ErrorCode.AwaitingAuth)
            {
                fncCallback(true, true, false);
                return;
            }
            // ..and Connection Id valid and authorised, return this
            // state info
            else if (intErrorCode == Chat.ErrorCode.None)
            {
                fncCallback(true, true, true);
                return;
            }
        }

        // For all other situations, claim server call failed            
        fncCallback(false, null, null);
    }
}

// =========================================================================
// RETRIEVE ENTRIES FROM SPECIFIED CONNECTION
// Callback Parameters:
//  Success     Boolean
//  Count       Int
// =========================================================================
Chat.GetTextCount = function(strId, fncCallback)
{
    // Ensure Id string specified
    if (!ObjectDetection.IsString(strId))
    {
        if (Chat.Debug)
            alert("Chat.GetTextCount: Invalid strId");
        return;
    }
    // Ensure callback method specified
    if (!ObjectDetection.IsFunction(fncCallback))
    {
        if (Chat.Debug)
            alert("Chat.GetTextCount: Invalid fncCallback");
        return;
    }
    
    // Make server call
    var arrParameters = new Array();
    arrParameters[0] = new Chat_DataRetrievals.DataRequestParameter("Action", Chat.ActionType.GetTextCount);
    arrParameters[1] = new Chat_DataRetrievals.DataRequestParameter("Id", strId);
    Chat_DataRetrievals.DataRequest("Chat.GetTextCount", arrParameters, CallbackWrapper, 3);
    
    // Prepare callback
    function CallbackWrapper(bSuccessServerCall, intErrorCode, strId, strInfo, intRetVal)
    {
        // If failed one way or another, return failure
        if ((!bSuccessServerCall)
         || (intErrorCode != Chat.ErrorCode.None)
         || (!ObjectDetection.IsInteger(intRetVal)))
        {
            fncCallback(false, null);
            return;
        }

        // Otherwise, return info
        fncCallback(true, intRetVal);
    }
}

// =========================================================================
// RETRIEVE ENTRIES FROM SPECIFIED CONNECTION
// Callback Parameters:
//  SuccessServerCall  Boolean
//  ValidIndex         Boolean
//  Index              Int
//  Content            String
// =========================================================================
Chat.GetText = function(strId, intIndex, fncCallback)
{
    // Ensure Id string specified
    if (!ObjectDetection.IsString(strId))
    {
        if (Chat.Debug)
            alert("Chat.GetText: Invalid strId");
        return;
    }
    // Ensure entry index specified
    if (!ObjectDetection.IsInteger(intIndex) || (intIndex < 0))
    {
        if (Chat.Debug)
            alert("Chat.GetText: Invalid intIndex");
        return;
    }
    // Ensure callback method specified
    if (!ObjectDetection.IsFunction(fncCallback))
    {
        if (Chat.Debug)
            alert("Chat.GetText: Invalid fncCallback");
        return;
    }
    
    // Make server call
    var arrParameters = new Array();
    arrParameters[0] = new Chat_DataRetrievals.DataRequestParameter("Action", Chat.ActionType.GetText);
    arrParameters[1] = new Chat_DataRetrievals.DataRequestParameter("Id", strId);
    arrParameters[2] = new Chat_DataRetrievals.DataRequestParameter("RetVal", intIndex);
    Chat_DataRetrievals.DataRequest("Chat.GetText", arrParameters, CallbackWrapper, 3);
    
    // Prepare callback
    function CallbackWrapper(bSuccessServerCall, intErrorCode, strId, strInfo, intRetVal)
    {
        // If failed contacting server (eg. server communication fail or
        // invalid input in some other way) return false server success
        if ((!bSuccessServerCall) || (intErrorCode != Chat.ErrorCode.None))
        {
            fncCallback(false, null, null, null);
            return;
        }

        // If returned string is null, but not failed above, then the
        // string index was invalid
        if (strInfo == null)
        {
            fncCallback(true, false, intRetVal, null);
            return;
        }

        // Otherwise, return success info
        fncCallback(true, true, intRetVal, strInfo);
    }
}

// =========================================================================
// PUSH ENTRY TO SPECIFIED CONNECTION
// Callback Parameters:
//  Success  Boolean
//  Index    Index of inserted entry
// =========================================================================
Chat.PushText = function(strId, strContent, fncCallback)
{
    // Ensure Id string specified
    if (!ObjectDetection.IsString(strId))
    {
        if (Chat.Debug)
            alert("Chat.PushText: Invalid strId");
        return;
    }
    // Ensure entry index specified
    if (!ObjectDetection.IsString(strContent))
    {
        if (Chat.Debug)
            alert("Chat.PushText: Invalid strContent");
        return;
    }
    // Ensure callback method specified
    if (!ObjectDetection.IsFunction(fncCallback))
    {
        if (Chat.Debug)
            alert("Chat.PushText: Invalid fncCallback");
        return;
    }

    // Encode content string for transmission
    strContent = Misc.HTMLEncode(strContent);
    
    // Make server call
    var arrParameters = new Array();
    arrParameters[0] = new Chat_DataRetrievals.DataRequestParameter("Action", Chat.ActionType.PushText);
    arrParameters[1] = new Chat_DataRetrievals.DataRequestParameter("Id", strId);
    arrParameters[2] = new Chat_DataRetrievals.DataRequestParameter("Content", strContent);
    Chat_DataRetrievals.DataRequest("Chat.PushText", arrParameters, CallbackWrapper, 3);
    
    // Prepare callback
    function CallbackWrapper(bSuccessServerCall, intErrorCode, strId, strInfo, intRetVal)
    {
        // If failed contacting server (eg. server communication fail or
        // invalid input in some other way) return false server success
        if ((!bSuccessServerCall)
         || (intErrorCode != Chat.ErrorCode.None)
         || (!ObjectDetection.IsInteger(intRetVal)))
        {
            fncCallback(false, null);
            return;
        }

        // Otherwise, return success info
        fncCallback(true, intRetVal);
    }
}

// =========================================================================
// TERMINATE SPECIFIED CONNECTION
// Callback Parameters:
//  Success  Boolean
// =========================================================================
Chat.Terminate = function(strId, fncCallback, bAsync)
{
    // Ensure Id string specified
    if (!ObjectDetection.IsString(strId))
    {
        if (Chat.Debug)
            alert("Chat.Terminate: Invalid strId");
        return;
    }

    // Optionally specify whether or not to make asynchronous call (default true)
    if (!ObjectDetection.IsBoolean(bAsync))
        bAsync = true;

    // Ensure callback method specified (if required)
    if (!bAsync)
      fncCallback = null;
    else if (!ObjectDetection.IsFunction(fncCallback))
    {
        if (Chat.Debug)
            alert("Chat.Terminate: Invalid fncCallback");
        return;
    }

    // Make server call
    var arrParameters = new Array();
    arrParameters[0] = new Chat_DataRetrievals.DataRequestParameter("Action", Chat.ActionType.Terminate);
    arrParameters[1] = new Chat_DataRetrievals.DataRequestParameter("Id", strId);
    // NB: If not making an asynchronous call, only allow a single attempt
    if (bAsync)
        Chat_DataRetrievals.DataRequest("Chat.Terminate", arrParameters, CallbackWrapper, 3, bAsync);
    else
        Chat_DataRetrievals.DataRequest("Chat.Terminate", arrParameters, CallbackWrapper, 1, bAsync);
    
    // Prepare callback
    function CallbackWrapper(bSuccessServerCall, intErrorCode, strId, strInfo, intRetVal)
    {
        var bSuccess = ((bSuccessServerCall) && (intErrorCode == Chat.ErrorCode.None))
        if (fncCallback != null)
            fncCallback(bSuccess);
    }
}
