'use strict';

angular.module('gms.logger', []).factory('loggerService',

	    function(preferencesService) {

	        var loggerService = function() {
	            var enabled = sessionStorage.getItem('enable-logger'); // null when not found
	            var storedLogs = []; // keep track of logs not printed because enabled is null

	            this.setEnabled = function(){
	            	// get config from CME
	            	preferencesService.getFlag('enable-logger', function(data){
		                if (data === true){
		                	enabled = "true";
		                	// print to console all the stored logs
		                	for (var i = 0; i < storedLogs.length; i++){
			                	console.log(storedLogs[i]);
			                }
			                storedLogs = []; //reset stored logs
		                }
		                else
		                	enabled = "false";
		                sessionStorage.setItem('enable-logger', enabled);
		            }, function(){
		            	enabled = null;
		            });
	            };
	            
	            this.logToConsole = function(line){
	            	// log line to console
	            	if (enabled === null){
	            		storedLogs.push(output);
	            		return;
	            	}
	            	if (enabled === "false")
	            		return;
	            	console.log(line);
	            };
	            
	            this.logHttpRequest = function(action, path, data, method, status, time){
	            	// log http request history to console
	            	var output = "Http Request History Log - " + time + "\n"
        							+ "\tAction: " + action + "\n" 
        							+ "\tPath: " + path + "\n"
        							+ "\tMethod: " + method  + "\n"
        							+ "\tStatus: " + status + "\n"
        							+ "\tData: " + JSON.stringify(data) + "\n";
	            	if (enabled === null){
	            		storedLogs.push(output);
	            		return;
	            	}
	            	if (enabled === "false")
	            		return;
	            	console.log(output);
	            };
	            
	            if (enabled === null)
	            	this.setEnabled();
	        };
 
	        return new loggerService();
});