/*
 * Sistema de Favoritos
 */
define([
	"exports",
	"dojo/json",
	"dojo/dom",
	"dojo/on",
	"dojo/ready",
	"dojo/fx/Toggler",
	"dijit/registry",
	"handsoft/utils",
	"handsoft/cutsa"
	], function(exports, JSON, dom, on, ready, Toggler, registry, utils, cutsa){
	var favourites = [];
	
	var favourites_storage_key = 'favourites';
	var favourites_data = window.localStorage.getItem(favourites_storage_key);
	
	if (favourites_data !== null){
		favourites = JSON.parse(favourites_data);
	}
	
	var empty_message_t = new Toggler({
        node: "favourites_empty"
    });
	
	var current_query = null;

	var current_multiple_query = null;
	
	var current_favourite = null;
	
	ready(function(){
		/* 
		 * Pagina Resultados: Boton 'back'
		 */
		var results_back_button = dom.byId("results_back_button");
		on(results_back_button, "click", function(evt){
			var v = registry.byId("results");
			v.performTransition('homepage', -1, "slide", null);
			
			current_favourite = null;
		});
		
		/* 
		 * Pagina Resultados: Boton Agregar/Quitar de Favoritos
		 */
		var results_favourite_button = dom.byId("results_favourite_button");
		on(results_favourite_button, "click", function(evt){
			if (current_favourite !== null){
				
				current_query = favourites[current_favourite];
				
				/* Borrando de favoritos */
				favourites.splice(current_favourite, 1);
				exports.store();
				
				exports.reload();
		
				current_favourite = null;
				current_multiple_query = null;
				utils.setFavouriteStatus(true);
			} else {
				/* Agrega la consulta actual a Favoritos */
				var itsok = false;
				
				if (current_multiple_query !== null){
					current_multiple_query.entries.forEach(function(entry, i){
						
						var fav = {
							"query": current_multiple_query.query,
							"params": entry
						};
						
						favourites.unshift(fav);
					});
					
					itsok = true;
					current_multiple_query = null;
				} else if (current_query !== null){					
					favourites.unshift(current_query);
					
					current_query = null;
					itsok = true;
				}
				
				if (itsok){
					exports.store();
					exports.reload();
				
					utils.setFavouriteStatus(false);
				}
			}
			
			exports.reload();
			
			// Activar solapa Favoritos
			registry.byId("home_accordion").expand(registry.byId("favourites_scroll"), false);
					
			// Redirigir al Home
			var v = registry.byId("results");
			v.performTransition('homepage', 1, "fade", null);
		});
	});
	
	exports.store = function(){
		/* Guarda los favoritos en el storage */
		favourites_data = JSON.stringify(favourites);
		window.localStorage.setItem(favourites_storage_key, favourites_data);
	};
	exports.setCurrent = function(query, params){
		/* Cambia la consulta actual */
		var new_query = {
			"query":query,
			"params": {}
		};

		for(var key in params){
			var attrName = key;
			var attrValue = params[key];
			
			new_query.params[attrName] = attrValue;
		}
		
		current_query = new_query;
	};
	exports.setCurrentMultiple = function(query, queries){
		current_multiple_query = {
			"query": query,
			"entries": queries
		};
	};
	exports.reload = function(){
		/* (Re)Carga los favoritos */
		var list = registry.byId("favourites_list");
		var scroll = registry.byId("favourites_scroll");
		
		while (list.domNode.hasChildNodes()) { //delete old items in list 
			list.domNode.removeChild(list.domNode.lastChild); 
		} 
		
		scroll.scrollTo({x:0, y:0});
		
		if (favourites.length == 0){
			empty_message_t.show();
			
			return;
		}
		
		empty_message_t.hide();
		
		favourites.forEach(function(entry, i){
			var title = utils.formatResult(entry);
			
			var item = new dojox.mobile.ListItem({
				clickable: true,
				selectable:false,
				onClick:function(){
					// Llamo al servicio
					cutsa.verifyToken(function(token){
						cutsa.queryService(entry.query, token, entry.params);
						utils.setFavouriteStatus(false);
						current_favourite = i;
					});
				},
				label:title
			});
			list.addChild(item);
		});
	};
	
	
	return exports;
});
