/**
 * Copyright (c) 2008-2011 The Open Planning Project
 * 
 * Published under the BSD license.
 * See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
 * of the license.
 */

/**
 * @requires plugins/Tool.js
 */

/** api: (define)
 *  module = gxp.plugins
 *  class = Logger
 */

/** api: (extends)
 *  plugins/Tool.js
 */
Ext.namespace("gxp.plugins");

/** api: constructor
 *  .. class:: Logger(config)
 *
 *    Provides an action to logger the map.
 */
gxp.plugins.Logger = Ext.extend(gxp.plugins.Tool, {
    
	LOG_LEVEL_INFO : 2, // сообщения об успешных запросах
	LOG_LEVEL_NETWORK_LOCAL_ERRORS : 1, // все ошибки
	//LOG_LEVEL_NETWORK_ERRORS : 0, // выводятся только сообщения о неверных запросах
	
    /** api: ptype = gxp_logger */
    ptype: "gxp_logger",

    /** api: config[loggerService]
     *  ``String``
     *  URL of the logger service.
     */
    loggerService: null,

    /** api: config[customParams]
     *  ``Object`` Key-value pairs of custom data to be sent to the logger
     *  service. Optional. This is e.g. useful for complex layout definitions
     *  on the server side that require additional parameters.
     */
    customParams: null,

    /** private: method[constructor]
     */
    constructor: function(config) {
        gxp.plugins.Logger.superclass.constructor.apply(this, arguments);
    },

    /** api: method[addActions]
     */
    addActions: function() {

		var me = this;		
		
		
        var actions = gxp.plugins.Logger.superclass.addActions.call(this, [{
				hidden: true,
                menuText: locale.labels.log.title,
                tooltip: locale.tips.showLog,
				id: "loggerButton",
                iconCls: "gxp-icon-logger",                
                handler: function() {
					var store = new Ext.data.ArrayStore ({
						fields: [
						   {name: 'time'},
						   {name: 'message'},
						   {name: 'level'}
						],
						data: log
					});
					
					var levels = new Ext.data.ArrayStore({
						fields: ["level", "description"],
						data: [
								[-1, locale.labels.log.noFilter],
								[gxp.plugins.Logger.prototype.LOG_LEVEL_INFO, locale.labels.log.infoFilter],
								[gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS, locale.labels.log.errorFilter]
						]
					});				
					
					var filter = new Ext.form.ComboBox({
						id: "logFilterCombobox",
						store: levels,
						valueField: "level",
						value: -1,
						displayField: "description",
						triggerAction: "all",						
						mode: "local",
						width: 300,
						listeners: {
							select: function(combo, record, index)
							{								
								if (filter.getValue()==-1) Ext.getCmp('logGrid').getStore().clearFilter();
								else Ext.getCmp('logGrid').getStore().filter("level",filter.getValue());  // set selected layers filter
							}
						}
					});
					new Ext.Window ({
						title: locale.labels.log.title,
						height: 400,
						width: 700,
						maximizable: true,
						layout: 'fit',
						tbar : {
							items: [								
								{
									xtype: 'label',
									html: locale.labels.log.filter + ":"
								},
								{
									xtype: 'tbspacer',
									width: 5
								},
								filter,
								{
									xtype: 'button',
									text: locale.labels.log.refresh,
									onClick: function() {
										Ext.getCmp('logGrid').getStore().removeAll();
										Ext.getCmp('logGrid').getStore().add(new Ext.data.ArrayStore ({
											fields: [
											   {name: 'time'},
											   {name: 'message'},
											   {name: 'level'}
											],
											data: log
										}).getRange());
										if (filter.getValue()==-1) Ext.getCmp('logGrid').getStore().clearFilter();
										else Ext.getCmp('logGrid').getStore().filter("level",filter.getValue());  // set selected layers filter
									}
								},
								{
									xtype: 'tbspacer',
									width: 5
								}
									
							]							
						},
						items: {
							xtype: 'grid',
							id : 'logGrid',
							autoExpandColumn: "log-message-column",							
							store: store,
							stateful: true,							
							columns: [
								{
									header     : locale.labels.log.timeColumn,
									sortable : true,
									dataIndex: 'time',
									renderer: Ext.util.Format.dateRenderer('H:i:s'),
									id: 'log-time-column'
								}, 
								{
									header     : locale.labels.log.messageColumn,
									flex     : 1,									
									dataIndex: 'message',
									id: 'log-message-column'									
								}
							]
						}
					}).show();
                },
                scope: this                
		}]);
          
        return actions;
        
    }

});


var formatDateTime = function(a, format) {			
	format = format || "HH:MM:SS";
	var day = ((a.getDate()).toString().length == 1 ? "0" + (a.getDate()) : a.getDate());			
	//var month = "02" ; // force february
	var month = ((a.getMonth()+1).toString().length == 1 ? "0" + (a.getMonth()+1) : a.getMonth()+1) ;
	var fullYear = a.getFullYear();
	var year= a.getYear();
	var hours = ((a.getHours()).toString().length == 1 ? "0" + (a.getHours()) : a.getHours());
	var mins = ((a.getMinutes()).toString().length == 1 ? "0" + (a.getMinutes()) : a.getMinutes()); 
	var seconds = ((a.getSeconds()).toString().length == 1 ? "0" + (a.getSeconds()) : a.getSeconds());
	return format
		.replace(/dd/g,day)
		.replace(/mm/g,month)
		.replace(/yyyy/g,fullYear)
		.replace(/yy/g,year)				
		.replace(/HH/g,hours)
		.replace(/MM/g,mins)
		.replace(/SS/g,seconds);
}


Ext.preg(gxp.plugins.Logger.prototype.ptype, gxp.plugins.Logger);
gxp.plugins.Logger.log = function(message, level) {
		
	var curdate = new Date();
	log.push ([ curdate, message, level]);
	var jsondata = {
		datetime: formatDateTime (curdate, "yyyy-mm-dd HH:MM:SS"),
		login: window.JOSSO_USER||"undefined",
		message: message,
	}

	GPOpenLayers.Request.issue({
        method: "POST",
        url: OVROOT + "services?service=actionLog&action=insert",
        async: true,        
        data: JSON.stringify(jsondata),        
        success: function(request) {},
		failure: function(){console.warn("Server log failed: " + message)}		
    });
}

gxp.plugins.Logger.logTile = function(message, level) {		
	var curdate = new Date();
	log.push ([ curdate, message, level]);
}

gxp.plugins.Logger.logRequest = function (config) {
	var level = config.status == "failure" ? gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS : gxp.plugins.Logger.prototype.LOG_LEVEL_INFO
	var date = new Date();
	var message = config.url;
	var serverError = "";
	if (config.status=="failure" && config.httpStatus) {
		serverError = "(Ответ сервера: "+config.httpStatus+": " + config.statusText + ")";
	}
	
	if (config.url.toLowerCase().indexOf("getcapabilities")+1) {
		if (config.status=="start") message =  locale.log.getCapabilitiesSent.replace("{0}",config.url);
		if (config.status=="success") message =   locale.log.capsRecieved.replace("{0}",config.url);
		if (config.status=="failure") message =   locale.log.capsError.replace("{0}",config.url) + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("getmap")+1) {
		if (config.status=="start") message =  locale.log.tileRequested.replace("{0}",config.url);
		if (config.status=="success") message = locale.log.tileReceived.replace("{0}",config.url);
		if (config.status=="failure") message = locale.log.tileError.replace("{0}",config.url) + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("getFeatureInfo")+1) {
		if (config.status=="start") message =  locale.log.featureInfoRequested.replace("{0}",config.url);
		if (config.status=="success") message = locale.log.featureInfoReceived.replace("{0}",config.url);
		if (config.status=="failure") message = locale.log.featureInfoError.replace("{0}",config.url) + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("getLegendGraphic")+1) {
		if (config.status=="start") message =  locale.log.legendRequested.replace("{0}",config.url);
		if (config.status=="success") message = locale.log.legendReceived.replace("{0}",config.url);
		if (config.status=="failure") message = locale.log.legendError.replace("{0}",config.url) + (serverError ? ". " + serverError : "") ;

	} else if (config.url.toLowerCase().indexOf("service=charts&action=getList")+1) {
		if (config.status=="start") message =  locale.log.chartsRequested;
		if (config.status=="success") message = locale.log.chartsReceived;
		if (config.status=="failure") message = locale.log.chartsError + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("service=animation&action=getList")+1) {
		if (config.status=="start") message =  locale.log.animationRequeted;
		if (config.status=="success") message = locale.log.animationReceived;
		if (config.status=="failure") message = locale.log.animationError + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("service=wms&action=getList")+1) {
		if (config.status=="start") message =  locale.log.wmsRequested;
		if (config.status=="success") message = locale.log.wmsReceived;
		if (config.status=="failure") message = locale.log.wmsError + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("service=arcgis&action=getList")+1) {
		if (config.status=="start") message =  locale.log.arcgisRequested;
		if (config.status=="success") message = locale.log.arcgisReceived;
		if (config.status=="failure") message = locale.log.arcgisError + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("service=rss&action=getList")+1) {
		if (config.status=="start") message =  locale.log.rssRequested;
		if (config.status=="success") message = locale.log.rssReceived;
		if (config.status=="failure") message = locale.log.rssError + (serverError ? ". " + serverError : "") ;
	}else if (config.url.toLowerCase().indexOf("service=aqua&action=getList")+1) {
		if (config.status=="start") message =  locale.log.aquaRequested;
		if (config.status=="success") message = locale.log.aquaReceived;
		if (config.status=="failure") message = locale.log.aquaError + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("service=rubricator")+1) { // рубрикатор, таблица toc
		if (config.status=="start") message =  locale.log.rubricatorRequested;
		if (config.status=="success") message = locale.log.rubricatorReceived;
		if (config.status=="failure") message = locale.log.rubricatorError + (serverError ? ". " + serverError : "") ;
	} else if (config.url.toLowerCase().indexOf("getFeature")+1) { // WFS выборка
		if (config.status=="start") message =  locale.log.featuresRequested.replace("{0}",config.url);
		if (config.status=="success") message = locale.log.featuresReceived.replace("{0}",config.url);
		if (config.status=="failure") message = locale.log.featuresError.replace("{0}",config.url) + (serverError ? ". " + serverError : "") ;
	} else {
		if (config.status=="start") message =  locale.log.requestSent.replace("{0}",config.url);
		if (config.status=="success") message = locale.log.responseGot.replace("{0}",config.url);
		if (config.status=="failure") message = locale.log.responseError.replace("{0}",config.url) + (serverError ? ". " + serverError : "") ;
	}
	log.push ([ date, message, level]);
}