<?php
Yii::app()->clientScript->registerCoreScript('cookie');
$isFullScreen = Yii::app()->getController()->action->id == 'fullScreen';

    $this->widget('ext.PlNavbar', array(
    //'type'=>'inverse', // null or 'inverse'
    'brand'=>__('SYSTEM_LOGVIEWER_SECTION_TITLE'),
    'fixed' => $isFullScreen ? 'top' : '',
    'items'=>array(
        array(
            'class'=>'bootstrap.widgets.TbMenu',
            'items'=>array(
                 array(
                     'label'=>'',
                     'url'=> $isFullScreen ? url('systemLogViewer') : url('systemLogViewer/default/fullScreen'),
                     'icon' => $isFullScreen ? 'resize-small' : 'resize-full',
                 ),
                array(
                    'label'=>__('SYSTEM_LOG_VIEWER_CLEAR_SCREEN'),
                    'url'=>'',
                    'icon' => 'file',
                    'itemOptions' => array(
                        'id' => 'clearScreen',
                        'data-translation-id'=>'SYSTEM_LOG_VIEWER_CLEAR_SCREEN',
                    ),
                ),
                array(
                    'label'=>__('SYSTEM_LOG_VIEWER_CLEAR_CACHE'),
                    'url'=>'',
                    'icon' => 'trash',
                    'itemOptions' => array(
                        'id' => 'clearDb',
                        'data-translation-id'=>'SYSTEM_LOG_VIEWER_CLEAR_CACHE',
                    ),
                ),
                array(
                    'label'=>__('SYSTEM_LOG_VIEWER_LOG_LEVEL_LABEL') . ' ' . $this->getCurrentLogLevelTitle(),
                    'url'=>'',
                    'icon' => 'reorder',
                    'active' => true,
                    'itemOptions' => array(
                        'id' => 'setLogLevel',
                        'data-translation-id'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_LABEL',
                        'data-translation-target'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_LIST',
                    ),
                    'items' => array(
                        array(
                            'label' => __('SYSTEM_LOG_VIEWER_LOG_LEVEL_DEBUG'),
                            'url'=>'',
                            'active'=>isset($_COOKIE['PhonalisaActiveLogLevel']) ? $_COOKIE['PhonalisaActiveLogLevel'] == 0 : true,
                            'itemOptions' => array(
                                'data-loglevel' => '0',
                                'data-translation-id'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_DEBUG',
                                'data-translation-target'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_LIST'
                            ),
                        ),
                        array(
                            'label' => __('SYSTEM_LOG_VIEWER_LOG_LEVEL_VERBOSE'),
                            'url'=>'',
                            'active'=>isset($_COOKIE['PhonalisaActiveLogLevel']) ? $_COOKIE['PhonalisaActiveLogLevel'] == 1 : false,
                            'itemOptions' => array(
                                'data-loglevel' => '1',
                                'data-translation-id'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_VERBOSE',
                                'data-translation-target'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_LIST'
                            ),
                        ),
                        array(
                            'label' => __('SYSTEM_LOG_VIEWER_LOG_LEVEL_WARNING'),
                            'url'=>'',
                            'active'=>isset($_COOKIE['PhonalisaActiveLogLevel']) ? $_COOKIE['PhonalisaActiveLogLevel'] == 2 : false,
                            'itemOptions' => array(
                                'data-loglevel' => '2',
                                'data-translation-id'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_WARNING',
                                'data-translation-target'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_LIST'
                            ),
                        ),
                        array(
                            'label' => __('SYSTEM_LOG_VIEWER_LOG_LEVEL_ERROR'),
                            'url'=>'',
                            'active'=>isset($_COOKIE['PhonalisaActiveLogLevel']) ? $_COOKIE['PhonalisaActiveLogLevel'] == 3 : false,
                            'itemOptions' => array(
                                'data-loglevel' => '3',
                                'data-translation-id'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_ERROR',
                                'data-translation-target'=>'SYSTEM_LOG_VIEWER_LOG_LEVEL_LIST'
                            ),
                        ),
                    ),
                ),
            ),
        ),
         '<form class="navbar-search pull-right" id="logSearchForm" data-translation-id="GLOBAL_SEARCH"><input type="text" class="search-query span2 placeholder-search-icon" placeholder="'. __('GLOBAL_SEARCH').'" id="filterText"></form>',
    ),
)); ?>




<script>
(function($) {
    // static myAwesomePlugin properties definition
    $.logViewer = {
        static_var: 'some value',
        // example of instances management
        // instances container
        instances: new Array(),
        // method to destroy all instances
        destroyAll: function() {
            $.each($.logViewer.instances, function(i, element) {
                element.myAwesomePlugin('destroy');
            });
        }
    };
    var methods = {
        init: function(options) {
            options = $.extend({}, $.fn.logViewer.defaults, options);
            return this.each(function(index, value) {
                // $this - jQuery instance of element
                var $this = $(this);
                // logViewer - instance of logViewer class
                var logViewer = $this.data('logViewer');
                // If the logViewer hasn't been initialized yet
                if (!logViewer) {
                    $this.data('logViewer', new LogViewer($this, options));
                    // push new element with inited jQuery logViewer to instances stack
                    $.logViewer.instances.push($this);
                }
            });
        },
        addMessage: function(message){
            return this.each(function(index, value) {
                // $this - jQuery instance of element
                var $this = $(this);
                // logViewer - instance of logViewer class
                var logViewer = $this.data('logViewer');
                // If the logViewer hasn't been initialized yet
                if (logViewer) logViewer.addMessage(message);
            });
        },
        say: function(message) {
            return this.each(function(index, value) {
                // $this - jQuery instance of element
                var $this = $(this);
                // logViewer - instance of logViewer class
                var logViewer = $this.data('logViewer');
                // If the logViewer hasn't been initialized yet
                if (logViewer) logViewer.say(message);
            });
        },
        filter: function(text) {
            return this.each(function(index, value) {
                // $this - jQuery instance of element
                var $this = $(this);
                // logViewer - instance of logViewer class
                var logViewer = $this.data('logViewer');
                // If the logViewer hasn't been initialized yet
                if (logViewer) logViewer.filter(text);
            });
        },
        setLogLevel: function(logLevel) {
            return this.each(function(index, value) {
                // $this - jQuery instance of element
                var $this = $(this);
                // logViewer - instance of logViewer class
                var logViewer = $this.data('logViewer');
                // If the logViewer hasn't been initialized yet
                if (logViewer) logViewer.setLogLevel(logLevel);
                $.cookie('PhonalisaActiveLogLevel', logLevel);
            });
        },
        setAutoScroll: function(autoScroll) {
            return this.each(function(index, value) {
                var $this = $(this);
                var logViewer = $this.data('logViewer');
                if (logViewer) logViewer.setAutoScroll(autoScroll);
            });
        },
        destroy: function() {
            return this.each(function() {
                // $this - jQuery instance of element
                var $this = $(this);
                // logViewer - instance of logViewer class
                var logViewer = $this.data('logViewer');
                // remove logViewer from instances
                if ($.inArray($.logViewer.instances, $this)) delete $.logViewer.instances[$.inArray($.logViewer.instances, $this)];
                // delete LogViewer instance
                delete logViewer;
                // remove link to LogViewer instance
                $this.removeData('logViewer');
            })
        },
        clear: function() {
            return this.each(function(index, value) {
                // $this - jQuery instance of element
                var $this = $(this);
                // logViewer - instance of logViewer class
                var logViewer = $this.data('logViewer');
                // If the logViewer hasn't been initialized yet
                if (logViewer) logViewer.clear();
            });
        },
        dropTable: function() {
            return this.each(function(index, value) {
                var $this = $(this);
                var logViewer = $this.data('logViewer');
                if (logViewer) logViewer.dropTable();
            });
        },
    };
    $.fn.logViewer = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.logViewer');
        }
    };
    // default logViewer options
    $.fn.logViewer.defaults = {
        option: 'option default value',
        findLimit: 1000,
        autoRender: true
    };
    var LogViewer = function(element, options) {
            var self = this;
            self.element = element;
            self.options = options;
            self.dataBase = null,
            self.filterText = '',
            self.logLevel = $.cookie('PhonalisaActiveLogLevel') ? $.cookie('PhonalisaActiveLogLevel') : 0,
            self.autoScroll = true,
            console.log('new LogViewer instance created');
            
            self.init = function(){
                var dbSize = 5 * 1024 * 1024; // 5MB
                self.dataBase = openDatabase("logViewer", "1.0", "Phonalisa LogViewer", dbSize);
            };
            
            self.createTable = function(){
                var db = self.dataBase;
                db.transaction(function(tx) {
                    tx.executeSql("CREATE TABLE IF NOT EXISTS " + "messages(ID INTEGER PRIMARY KEY ASC, message TEXT, logtag INTEGER, level TEXT, time DATETIME)", []);
                });
            };
            
            self.onError = function(tx, e) {
                console.warn("There has been an error: " + e.message);
            }

            self.onSuccess = function(tx, r) {
                // re-render the data.
                // loadTodoItems is defined in Step 4a
                //html5rocks.webdb.getAllTodoItems(loadTodoItems);
                if(self.options.autoRender == true){
                    //console.log(r);
                    //self.loadMessages();
                    //self.renderMessage();
                }
            }
            
            self.onNewItemAdded = function(tx, r) {
                //console.log(tx);
                //console.log(r);
                
                self.loadMessages(r.insertId);
                /*

                console.log('data successfully added to db');                
                if(self.options.autoRender == true){
                    //console.log(r);
                    //self.loadMessages();
                    //self.renderMessage();
                }
*/
            }
            
            self.renderMessage = function(tx, results) {                
                var msgHtml = '';

                var len = results.rows.length, i;
                
                for (i = len-1; i >= 0; i--){
                    var msg = results.rows.item(i);                  
                    msgHtml += formatDate(msg.time) + "\t" + self.logLevelToText(msg.level) + "\t" + msg.message + "\n";
                }
                
                //for (i = 0; i < len; i++){
                //    var msg = results.rows.item(i);                  
                //    msgHtml += formatDate(msg.time) + "\t" + self.logLevelToText(msg.level) + "\t" + msg.message + "\n";
                //}
                self.element.text(self.element.text() + msgHtml);
                
                if(self.autoScroll){
                    self.scrollDown();    
                }
                
            },
            self.renderRecordsCount = function(tx, results) {                               
                var len = results.rows.length;

                var num = results.rows.item(0).c;
                self.element.append(num + " records in cache...\n");        
            },
            self.loadMessages = function(id){
                if (!window.openDatabase) {
                    return;
                }
            
            
                var db = this.dataBase;
                db.transaction(function(tx){
                    tx.executeSql(self.createQuery(id), [], self.renderMessage, self.onError);
                });            
            },
            self.createQuery = function(id){
                var query = 'SELECT * FROM messages';
                
                query += " WHERE level >= " + self.logLevel + '.0';
                
                if(self.filterText != ''){
                    query += " AND message like '%" + self.filterText + "%'";
                }
                
                if(id != undefined){
                    query += " AND id = " + id;
                }              
                
                query += " ORDER by ID DESC";
                
                if(self.options.findLimit != 0){
                    query += " LIMIT " + self.options.findLimit; 
                }
                
                //console.log(query);
                return query;
            },
            self.logLevelToText = function(level){
                var logLevelTitle;
                
                switch(parseInt(level)){
                    case 0:
                        logLevelTitle = "DEBUG";
                        break;
                    case 1:
                        logLevelTitle = "VERBOSE";
                        break;
                    case 2:
                        logLevelTitle = "WARNING";
                        break;
                    case 3:
                        logLevelTitle = 'ERROR';
                        break;
                    default:
                        logLevelTitle = 'DEBUG';
                        break;
                }                
                return logLevelTitle;
            },
            self.logLevelToInt = function(level){
                logLevel = 0;
                switch (level){
                    case "DEBUG":
                        logLevel = 0;
                        break;
                    case "VERBOSE":
                        logLevel = 1;
                        break;
                    case "WARNING":
                        logLevel = 2;
                        break;
                    case "ERROR":
                        logLevel = 3;
                        break;
                    default:
                        logLevel = 0;
                        break;
                }
                
                return logLevel;
            },
            self.filter = function(text){
                self.clear();
                self.filterText = text;
                self.loadMessages();
            },
            self.setLogLevel = function(logLevel){
                self.clear();
                self.logLevel = logLevel;
                self.loadMessages();
            },
            self.setAutoScroll = function(autoScroll){
                self.autoScroll = autoScroll;
            }
            self.countRecords = function(){
                var db = this.dataBase;
                db.transaction(function(tx){
                    var query = "SELECT COUNT(*) AS c FROM messages";
                    tx.executeSql(query, [], self.renderRecordsCount, self.onError);
                });
            }
            
            if (window.openDatabase) {
                self.init();
                self.createTable();
                self.countRecords();    
            } else {
                console.log('WEBSQL NOT SUPPORTED');
                $('#filterText, #clearDb, #clearScreen').hide();
            }
        };
    LogViewer.prototype = {
        element: undefined,
        options: undefined,
        say: function(message) {
            var self = this;
            var m = self.element.text() + message + "\n"; 
            self.element.html(m);
        },
        clear: function() {
            var self = this;
            self.element.html('');
        },
        dropTable: function() {
            var self = this;
            //self.clear();
            var db = this.dataBase;
            db.transaction(function(tx){
                tx.executeSql('DROP TABLE messages');
            });
            
            self.createTable();
            self.element.html("DB reseted...\n");
        },
        addMessage: function(msg) {       
            
            var self = this;
            var db = this.dataBase;
            var logLevel;
            
            // disable trim for performance            
            switch (msg.level){
                case "DEBUG":
                    logLevel = 0;
                    break;
                case "VERBOSE":
                    logLevel = 1;
                    break;
                case "WARNING":
                    logLevel = 2;
                    break;
                case "ERROR":
                    logLevel = 3;
                    break;
                default:
                    logLevel = 0;
                    break;
            }
            
            if (!window.openDatabase) {
                if(self.logLevel <= logLevel){
                    var msgHtml = '';
                    msgHtml += formatDate(msg.time) + "\t" + msg.level + "\t" + msg.text + "\n"; 
                    self.element.append(msgHtml);
                
                    if(self.autoScroll){
                        self.scrollDown();    
                    }
                }
                

                return;    
            }
            
            
            db.transaction(function(tx){
                var addedOn = new Date();
                tx.executeSql("INSERT INTO messages(message, level, logtag, time) VALUES (?,?,?,?)", [msg.text, logLevel, msg.logtag, msg.time], self.onNewItemAdded, self.onError);
            });
            
            
        },
        scrollDown: function(){
            var el = this.element.context;
            el.scrollTop = el.scrollHeight;
        },
        _: ''
    };
})(jQuery);





function formatDate(d){
    d = d *1000;

  if(typeof d === 'number') d = new Date(d);
  if(!(d instanceof Date)) return d;
  function pad(n){return n<10 ? '0'+n : n}
  return pad(d.getMonth()+1)+'/'
        + pad(d.getDate())+'/'
        + d.getFullYear()+" "
        + pad(d.getHours()) + ":"
        + pad(d.getMinutes()) + ":"
        + pad(d.getSeconds());
}


$(function() {

    $('#logView').logViewer();
    
    $('#clearScreen').click(function(){
        $('#logView').logViewer('clear');
    });
    
    $('#clearDb').click(function(){
        $('#logView').logViewer('dropTable');
    });
    
        
    $("#filterText").on("paste", function(){
        $('#logView').logViewer('filter', $(this).val());
    });
    
    $("#filterText").on("keyup", function(event){
        if (event.keyCode == '13') {
            event.preventDefault();
            $('#logView').logViewer('filter', $(this).val());
        }
        return false;
    });
    
    
    $('#setLogLevel li').click(function(){
        var el = $(this);
        $(this).parent().find('li').removeClass('active');
        el.addClass('active');
        var logLevel = el.data('loglevel');
        var logLevelTitle;
        
        switch(logLevel){
            case 0:
                logLevelTitle = '<?php echo __("SYSTEM_LOG_VIEWER_LOG_LEVEL_DEBUG")?>';
                break;
            case 1:
                logLevelTitle = '<?php echo __("SYSTEM_LOG_VIEWER_LOG_LEVEL_VERBOSE")?>';
                break;
            case 2:
                logLevelTitle = '<?php echo __("SYSTEM_LOG_VIEWER_LOG_LEVEL_WARNING")?>';
                break;
            case 3:
                logLevelTitle = '<?php echo __("SYSTEM_LOG_VIEWER_LOG_LEVEL_ERROR")?>';
                break;
            default:
                logLevelTitle = '<?php echo __("SYSTEM_LOG_VIEWER_LOG_LEVEL_DEBUG")?>';
                break;
        }
        
        $('#logView').logViewer('setLogLevel', logLevel);
        $('#setLogLevel > a').html('<i class="icon-reorder"></i>&nbsp;<?php echo __("SYSTEM_LOG_VIEWER_LOG_LEVEL_LABEL")?> ' + logLevelTitle) + '&nbsp;<span class="caret"></span>';
    });
    
    
    $('#logSearchForm').submit( function( e ) {
        e.preventDefault();
    });
    
    
    $('#logView').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(e){
        if ( e.which > 0 || e.type == "mousedown" || e.type == "mousewheel"){
            var container = $(this);
            
            var height = container.height();
            var scrollHeight = container[0].scrollHeight;
            var st = container.scrollTop();
            
            //alert(st >= scrollHeight - height);
            //$("#logView").stop();
            //console.log(st >= scrollHeight - height);
            $('#logView').logViewer('setAutoScroll', st >= scrollHeight - height - 10);
            //console.log(st >= scrollHeight - height - 10);

        }
    });






var logWs;
if ('WebSocket' in window){

    setTimeout(function() {

        var callCommand = {
                name: "subscribeLogfile",
                type: "command",
                uuid: "generate it later",  
        };
        ws.command(callCommand);
    }, 1000);
    
    ws.subscribe('logMessage', null, function(obj) {
            $('#logView').logViewer('addMessage', {
                text: obj.logmsg.logtag + "\t" + obj.logmsg.msg,
                time: obj.datetime,
                level: obj.logmsg.level,
                logtag: obj.logmsg.logtag,
            });
    });


}

// init
/*
$('#logView').myAwesomePlugin();

// method calls
$('<css-selector>').myAwesomePlugin('say', 'Hello, I\' awesome jQuery plugin');
$('<css-selector>').myAwesomePlugin('someOtherMethod', {
    param1: 'value1',
    param2: 'value2'
}); 
$('<css-selector>').myAwesomePlugin('destroy');
*/

// mass methods call

    

});
</script>

<style>
#logView{
    width: 100%;
    height: 100%;
    min-height: 500px;
    background-color: #000;
    color: #bbb;
    cursor: default;
    font-size: 12px;
    font-family: fixedsys, courier new, courier, verdana, helvetica, arial, sans-serif;
}
</style>

<textarea id="logView" disabled="disabled"></textarea>

<?php
    if(Yii::app()->getController()->action->id == 'fullScreen'){
?>
    <style>
    #logView{
        padding: 0;
        margin: 0;
        border: none;
        margin-top: 40px;
        padding-top: 5px;
    }
    </style>
<?php
    }
?>
