﻿/*
Central manager class handling all log entries
*/

var LogManager = Class.create();

LogManager.prototype =
{
    // Constructor
    initialize : function()
    {
        // Declare variable indicating if logging is enabled
        this.Enabled = false;
        
        // Declare Array variable holding the log entrees
        this._logEntries = new Array();
        
        // Declare variable holding the log window
        this._win;
        
        // Declare variables holding the diferent log type tables
        this._completeTable;
        this._alertTable;
        this._exceptionTable;
        this._errorTable;
        this._notificationTable;
        
        // Call BuildLogWindow function
        this.BuildLogWindow();
    },
    
    WriteAlert : function(piMessageKey, piFunctionName, piFunctionParams, piEntityType, piEntityId, piShowMessage)
    {
        // Create new LogEntry object
        var entry = new LogEntry('ALERT', piFunctionName, piFunctionParams, piMessageKey, piEntityType, piEntityId);
        
        if((piShowMessage != null) && (piShowMessage == true))
        {
            entry.ShowMessage();
        }
        
        if(this.Enabled == false)
        {
            return;
        }
        
        // Push the log entry into _logEntries Array
        this._logEntries.push(entry);
        // Add the log entry to the log window
        
        this.AddEntry(entry);
    },
    
    WriteException : function(piMessageKey, piFunctionName, piFunctionParams, piEntityType, piEntityId, piException, piShowMessage)
    {      
        // Create new LogEntry object
        var entry = new LogEntry('EXCEPTION', piFunctionName, piFunctionParams, piMessageKey, piEntityType, piEntityId, piException);
        
        if((piShowMessage != null) && (piShowMessage == true))
        {
            entry.ShowMessage();
        }
        
        if(this.Enabled == false)
        {
            return;
        }
        
        // Push the log entry into _logEntries Array
        this._logEntries.push(entry);
        // Add the log entry to the log window
        this.AddEntry(entry);
    },
    
    WriteError : function(piMessageKey, piFunctionName, piFunctionParams, piEntityType, piEntityId, piShowMessage)
    {
        // Create new LogEntry object
        var entry = new LogEntry('ERROR', piFunctionName, piFunctionParams, piMessageKey, piEntityType, piEntityId, piShowMessage);
        
        if((piShowMessage != null) && (piShowMessage == true))
        {
            entry.ShowMessage();
        }
        
        if(this.Enabled == false)
        {
            return;
        }
        
        // Push the log entry into _logEntries Array
        this._logEntries.push(entry);
        // Add the log entry to the log window
        this.AddEntry(entry);
    },
    
    WriteNotification : function(piMessageKey, piFunctionName, piFunctionParams, piEntityType, piEntityId, piShowMessage)
    {
        // Create new LogEntry object
        var entry = new LogEntry('NOTIFICATION', piFunctionName, piFunctionParams, piMessageKey, piEntityType, piEntityId);
        
        if((piShowMessage != null) && (piShowMessage == true))
        {
            entry.ShowMessage();
        }
        
        if(this.Enabled == false)
        {
            return;
        }
        
        // Push the log entry into _logEntries Array
        this._logEntries.push(entry);
        // Add the log entry to the log window
        this.AddEntry(entry);
    },
    
    BuildLogWindow : function()
    {
        // Create a window holding the log entry list
        this._win = new WebWindow('Logs');
        this._win.Width = 650;
        this._win.Height = 400;
        this._win.zIndex = 2000;
        this._win.CenterScreen = true;
        this._win.MakeDraggable = true;
        
        // Create new WebTabCollection for the different log types
        var tabs = new WebTabCollection();
        
        // Create a new WebTab for each log type
        tabs.AddTab('All Log Entries');
        tabs.AddTab('Alerts');
        tabs.AddTab('Exceptions');
        tabs.AddTab('Errors');
        tabs.AddTab('Notifications');
        
        // Create a new table for each log type and one for all log entries
        this._completeTable = Builder.node('table', { cellspacing: '0', cellpadding: '4px' });
        this._completeTable.className = 'LogTable';
        this._alertTable = Builder.node('table', { cellspacing: '0', cellpadding: '4px' });
        this._alertTable.className = 'LogTable';
        this._exceptionTable = Builder.node('table', { cellspacing: '0', cellpadding: '4px' });
        this._exceptionTable.className = 'LogTable';
        this._errorTable = Builder.node('table', { cellspacing: '0', cellpadding: '4px' });
        this._errorTable.className = 'LogTable';
        this._notificationTable = Builder.node('table', { cellspacing: '0', cellpadding: '4px' });
        this._notificationTable.className = 'LogTable';
        
        // Create containers and column headers for each table
        var completeContainer = Builder.node('div', { style: 'height:350px;overflow:auto;' });
        var alertContainer = Builder.node('div', { style: 'height:350px;overflow:auto;' });
        var exceptionContainer = Builder.node('div', { style: 'height:350px;overflow:auto;' });
        var errorContainer = Builder.node('div', { style: 'height:350px;overflow:auto;' });
        var notificationContainer = Builder.node('div', { style: 'height:350px;overflow:auto;' });
        
        // Add the tables to the containers
        completeContainer.appendChild(this._completeTable);
        alertContainer.appendChild(this._alertTable);
        exceptionContainer.appendChild(this._exceptionTable);
        errorContainer.appendChild(this._errorTable);
        notificationContainer.appendChild(this._notificationTable);
        
        // Create table headers
        var completeHeader = this.BuildHeader();
        var alertHeader = this.BuildHeader();
        var exceptionHeader = this.BuildHeader();
        var errorHeader = this.BuildHeader();
        var notificationHeader = this.BuildHeader();
        
        // Add the tables to the different WebTabs     
        tabs.Tabs['All Log Entries'].appendChild(completeHeader);
        tabs.Tabs['All Log Entries'].appendChild(completeContainer);
        tabs.Tabs['Alerts'].appendChild(alertHeader);
        tabs.Tabs['Alerts'].appendChild(alertContainer);
        tabs.Tabs['Exceptions'].appendChild(exceptionHeader);
        tabs.Tabs['Exceptions'].appendChild(exceptionContainer);
        tabs.Tabs['Errors'].appendChild(errorHeader);
        tabs.Tabs['Errors'].appendChild(errorContainer);
        tabs.Tabs['Notifications'].appendChild(notificationHeader);
        tabs.Tabs['Notifications'].appendChild(notificationContainer);
        
        // Append the WebTabCollection to the WebWindow
        this._win.appendChild(tabs.GetHtml());
    },
    
    AddEntry : function(piEntry)
    {
        // Create entry variable to hold the current entry
        var entry = piEntry;
        if(entry == null)
        {
            return;
        }
        
        // Create variable holding color of the lof entry row in the complete table
        var rowColor;
        // Check the type of the current entry
        switch(entry.Type.toUpperCase())
        {
            case('ALERT'):
                rowColor = '#D4B81F';
                break;
            case('EXCEPTION'):
                rowColor = '#FF0000';
                break;
            case('ERROR'):
                rowColor = '#D46C1F';
                break;
            case('NOTIFICATION'):
                rowColor = '#000000';
                break;
        }
        
        // Create a new table row for the complete table
        var currentRow = this._completeTable.insertRow(0);//var currentRow = this._completeTable.insertRow(completeTable.rows.length);
        currentRow.style.color = rowColor;
        Event.observe(currentRow, 'mouseover', function(piEvent){ var targetElem = Event.findElement(piEvent, 'tr'); if(!targetElem){ return; } targetElem.style.backgroundColor = '#BDDFE7'; targetElem.style.cursor = 'pointer'; });
        Event.observe(currentRow, 'mouseout', function(piEvent){ var targetElem = Event.findElement(piEvent, 'tr'); if(!targetElem){ return; } targetElem.style.backgroundColor = 'transparent';  targetElem.style.cursor = 'auto'; });
        Event.observe(currentRow, 'click', entry.Show.bindAsEventListener(entry));
        
        // Create table cells for each log entry field
        var cell_Type = currentRow.insertCell(currentRow.cells.length)
        var cell_Date = currentRow.insertCell(currentRow.cells.length)
        var cell_Time = currentRow.insertCell(currentRow.cells.length);
        var cell_Function = currentRow.insertCell(currentRow.cells.length);
        var cell_EntityType = currentRow.insertCell(currentRow.cells.length);
        var cell_LogMessage = currentRow.insertCell(currentRow.cells.length);
        
        // Fill the table cells
        cell_Type.appendChild(document.createTextNode(entry.Type.capitalize()));
        cell_Date.appendChild(document.createTextNode(entry.Date.getDate() + '.' + entry.Date.getMonth() + '.' + entry.Date.getFullYear()));
        cell_Time.appendChild(document.createTextNode(entry.Date.getHours() + ':' + entry.Date.getMinutes() + ':' + entry.Date.getSeconds()+ ':' + entry.Date.getMilliseconds().toString().slice(0,2)));
        cell_Function.appendChild(document.createTextNode(entry.FunctionName.truncate(18)));
        cell_EntityType.appendChild(document.createTextNode(entry.EntityType));
        cell_LogMessage.appendChild(document.createTextNode(entry.MessageKey.truncate(18)));
        
        
        // Create variable holding the typed table which will hold the current entry
        var typedTable;
        // Check the type of the current entry
        switch(entry.Type.toUpperCase())
        {
            case('ALERT'):
                typedTable = this._alertTable;
                break;
            case('EXCEPTION'):
                typedTable = this._exceptionTable;
                break;
            case('ERROR'):
                typedTable = this._errorTable;
                break;
            case('NOTIFICATION'):
                typedTable = this._notificationTable;
                break;
        }
        
        // Create a new table row for the typed table
        var currentRow = typedTable.insertRow(0);
        Event.observe(currentRow, 'mouseover', function(piEvent){ var targetElem = Event.findElement(piEvent, 'tr'); if(!targetElem){ return; } targetElem.style.backgroundColor = '#BDDFE7';  targetElem.style.cursor = 'pointer';});
        Event.observe(currentRow, 'mouseout', function(piEvent){ var targetElem = Event.findElement(piEvent, 'tr'); if(!targetElem){ return; } targetElem.style.backgroundColor = 'transparent';  targetElem.style.cursor = 'auto';});
        Event.observe(currentRow, 'click', entry.Show.bindAsEventListener(entry));
        
        // Create table cells for each log entry field
        var cell_Type = currentRow.insertCell(currentRow.cells.length)
        var cell_Date = currentRow.insertCell(currentRow.cells.length)
        var cell_Time = currentRow.insertCell(currentRow.cells.length);
        var cell_Function = currentRow.insertCell(currentRow.cells.length);
        var cell_EntityType = currentRow.insertCell(currentRow.cells.length);
        var cell_LogMessage = currentRow.insertCell(currentRow.cells.length);
        
        // Fill the table cells
        cell_Type.appendChild(document.createTextNode(entry.Type.capitalize()));
        cell_Date.appendChild(document.createTextNode(entry.Date.getDate() + '.' + entry.Date.getMonth() + '.' + entry.Date.getFullYear()));
        cell_Time.appendChild(document.createTextNode(entry.Date.getHours() + ':' + entry.Date.getMinutes() + ':' + entry.Date.getSeconds()+ ':' + entry.Date.getMilliseconds().toString().slice(0,2)));
        cell_Function.appendChild(document.createTextNode(entry.FunctionName.truncate(18)));
        cell_EntityType.appendChild(document.createTextNode(entry.EntityType));
        cell_LogMessage.appendChild(document.createTextNode(entry.MessageKey.truncate(18)));
    },
    
    ShowLogWindow : function()
    {
        // Check if logging is enabled
        if(this.Enabled == false)
        {
            // Show Message
            var msg = new WebMessage('Info', 'Logging has been disabled!');
            msg.Show();
            return;
        }
        
        // Append the window's html node to the document body
        document.body.appendChild(this._win.GetHtml())
    },
    
    BuildHeader : function()
    {
        var completeHeader = Builder.node('table', { cellspacing: '0', cellpadding: '4px' });
        completeHeader.className = 'LogHeader';
        var headerRow = completeHeader.insertRow(completeHeader.rows.length);
        // Create header cells
        var headercell_Type = headerRow.insertCell(headerRow.cells.length)
        var headercell_Date = headerRow.insertCell(headerRow.cells.length)
        var headercell_Time = headerRow.insertCell(headerRow.cells.length);
        var headercell_Function = headerRow.insertCell(headerRow.cells.length);
        var headercell_EntityType = headerRow.insertCell(headerRow.cells.length);
        var headercell_LogMessage = headerRow.insertCell(headerRow.cells.length);
        // Fill header cells
        headercell_Type.appendChild(document.createTextNode('Log Type'));
        headercell_Date.appendChild(document.createTextNode('Date'));
        headercell_Time.appendChild(document.createTextNode('Time'));
        headercell_Function.appendChild(document.createTextNode('Source'));
        headercell_EntityType.appendChild(document.createTextNode('Entity Type'));
        headercell_LogMessage.appendChild(document.createTextNode('Message'));
        
        return completeHeader;
    },
    
    OnListItemClick : function(piEvent)
    {
        // Get the element being the source of the event and return if it is null
        var targetElem = Event.findElement(piEvent, 'tr');
        if(!targetElem)
            return;
            
        // Get the log entry id
        var entryId = targetElem.entryId;
        if(entryId == null)
        {
            return;
        }
        
        // Get the log entry
        var entry = this._logEntries[entryId];
        
        // Show the log entry
        entry.Show();
    }
}