//  @import com.hedgehoglab.application.controller.BaseController;
//	@import com.hedgehoglab.application.helper.BaseHelper;
// @import com.hedgehoglab.utils.Async;

function DealsController(scope){
	BaseHelper.call(this,scope);
	BaseController.call(this,scope);
	var _lookups=null;
	var _users_lookup=null;
	
	var _deal=null;
	var _filter_by=0;
	
	var _visible_list=null;
	var _filtered_list=null;
	var _groups=null;
	// var _groups_lookup
	var _new_deal=null;

	
	//	Index's of the current working deals
	var _contacts_lookup={};
	
	var _working_deals=[];
	var _deals_lookup=null;
	var _deals=[];
	
	var _deals_notes_lookup={};
	var _deals_tasks_lookup={};
	var _deals_contacts_lookup={};
	var _deals_users_lookup={};
	var _deals_companies_lookup={};
	
	var _task_types_lookup={};
	
	var _deals_group_lookup={};		//	Stores a lookup for the group each deal is in
	
	var _selected=[];
	var _selected_lookup={};

	var _groups=[
		{
			"css":"inprogress",
			"title":"In Progress",
			"deals":{},
			"deals_count":0,
			"order":[],
			"index":0
		},
		{
			"css":"won",
			"title":"Won",
			"deals":{},
			"deals_count":0,
			"order":[],
			"index":1
		},
		{
			"css:":"lost",
			"title":"Lost",
			"deals":{},
			"deals_count":0,
			"order":[],
			"index":2
		}
	];
	var _groups_lookup={};
	var _groups_selected_lookup=[0,0,0];
	var _groups_selected_deals_lookup=[[],[],[]];
	
	var _this=this;
	//	Store the lookups outside of the services
	//	We need the following lookups!
	//	* All Contacts
	//	* All Companies
	//	* All Users
	//	* All Deals
	
	//	Local lookups are updated when...
	//	The filter for the geroup changes!
	function update_local_lookups(){
		//	create each group
		//	clear each group
		//	determine which group each of the selected items in in
	}
	
	
	scope.deals_list_view.subscribe_to('on_selected_deals_changed',function(e){
		_selected=e.model;
		_selected_lookup={};
		
		build_selected_indeces();
		
	    scope.deals_edit_view.show_loading();
		rerender_edit_view();
	});

	function build_selected_indeces(){
		//	If we've only selected 1 item then all groups need clearing else
		//	we are selecting multiple and the groups lists need to persist
		// _groups_selected_lookup=[0,0,0];
		_groups_selected_flags=[false,false,false];
		
		if(_selected.length<=1){
			_groups_selected_lookup=[0,0,0];
			_groups_selected_deals_lookup=[[],[],[]];
		}
		
		$.each(_selected,function(i,deal_id){
			//	get the group id of this deal
			group_index=_deals_group_lookup[deal_id];
			
			if(_groups_selected_flags[group_index]==false){
				//	Clear teh group
				_groups_selected_lookup[group_index]=0;
				_groups_selected_deals_lookup[group_index]=[];
				_groups_selected_flags[group_index]=true
			}
			
			_selected_lookup[deal_id]=true;
			_groups_selected_lookup[group_index]++;
			_groups_selected_deals_lookup[group_index].push(deal_id);
		});	
	}
	
	//	Re-render the edit view based on what is selected from the current filter
	function rerender_edit_view(dont_reload){

		var sel_count=0;
		
		var _sele_deal={};
		// alert(_filter_by);
		var _groups_by_filter=groups_by_filter(_filter_by);
		// _groups_selected_lookup
		$.each(_groups_by_filter,function(gindex,group){
			// if(group!=null){
				sel_count+=_groups_selected_lookup[group.index];
			// }
		});
		
		if(sel_count==0){
			scope.deals_edit_view.render_no_deals();
		}else if(sel_count==1){
			// _deal={model:_sele_deal[0]};
			
			function render_the_deal(){
				// var _model=$.extend({},_lookups,{deal:_sele_deal[0]},{users:_users_lookup})


				var _model={
					deals:_deals_lookup,
					deal:_selected[0],
					users:_users_lookup,
					deals_users_lookup:_deals_users_lookup[_selected[0]],
					contacts:_deals_contacts_lookup[_selected[0]],
					all_contacts:_contacts_lookup,
					companies:_deals_companies_lookup[_selected[0]],
					notes:_deals_notes_lookup[_selected[0]],
					tasks:_deals_tasks_lookup[_selected[0]],
					task_types:_task_types_lookup
				}
				scope.deals_edit_view.render_one_deal(_model);
			}
			
			if(dont_reload){
				render_the_deal();
			}else{
				load_data_for_one_deal(_selected[0],function(e){
					render_the_deal();
				});
			}
			
		}else if(sel_count>1){
			/*
			deals:_deals_lookup,
			deal:_selected[0],
			users:_users_lookup,
			*/
			var _model=$.extend({},{groups:_groups_by_filter,deals:_deals_lookup,users:_users_lookup,
				groups_selected_lookup:_groups_selected_lookup,
				groups_selected_deals_lookup:_groups_selected_deals_lookup
				});
			// var _model=$.extend({},_lookups,{deal:_sele_deal,users:_users_lookup,groups:_filtered_list});
			scope.deals_edit_view.render_many_deals(_model);
		}
	}
	
	function load_data_for_one_deal(deal_id,callback){
		var _delegates=[];
		
		// Load notes for deal
		_delegates.push(function(e){
			scope.deals_service.get_notes_lookup_for_deal(deal_id,function(notes){
				_deals_notes_lookup[deal_id]=notes;
				e();
			});
		});
		
		// Load tasks for deal
		_delegates.push(function(e){
			scope.deals_service.get_tasks_lookup_for_deal(deal_id,function(tasks){
				_deals_tasks_lookup[deal_id]=tasks;
				e();
			});
		});
		
		// Load contacts for deal
		_delegates.push(function(e){
			scope.deals_service.get_contacts_lookup_for_deal(deal_id,function(contacts){
				// console.warn("HAHAHAHAHAHAH >>>>>>>>> ",contacts)
				_deals_contacts_lookup[deal_id]=contacts;
				e();
			});
		});
		
		_delegates.push(function(e){
			scope.contacts_service.get_contacts_lookup(function(contacts){
				_contacts_lookup=contacts;
				e();
			});
		});
		
		
		_delegates.push(function(e){
			scope.deals_service.get_users_lookup_for_deal(deal_id,function(users_lookup){
				_deals_users_lookup[deal_id]=users_lookup;
				e();
			});
		});
		
		// Reload users each time (Incase users have been disabled / added or changed)
		_delegates.push(function(e){
			scope.users_service.get_all_users_lookup(function(users){
				_users_lookup=users;
				e();
			});
			// scope.deals_service.get_users_lookup_for_deal(deal_id,function(users_lookup){
			// 	_deals_users_lookup[deal_id]=users_lookup;
				
			// });
		});
		
		// http://localhost:8080/api/deals/2/contacts/
		// 		
		Async.multi_thread_load(_delegates,function(){
			callback();
		});
	};
	
	scope.deals_actions_view.subscribe_to('on_new_deal_clicked',function(e){
	
		scope.licence_service.can_add_deals(function(can_add_deals,check){
		
			if(can_add_deals){
				//	Get a new deal from the service!
				scope.deals_service.get_new_deal(function(new_deal){
					_new_deal=new_deal;
					scope.deals_list_view.disable();

					//	Need to pass in the companies, contacts and users here!
					scope.deals_edit_view.edit({
						deal:new_deal,users:_users_lookup
					});
				});
			}else{
				//
				//feedback.contacts.index.importlicencefail
				var message = _this.resource_string("feedback.deals.index.addlicencefail");
			    scope.message_service.show_message({
			        message: message,
			        type: "info"
			    });
			}
			
		
		});
		
	});
	
	scope.deals_edit_view.subscribe_to('on_cancel_edit_clicked',function(e){
		//	Delete the new deal!
		//	Enable the GUI
		if(_new_deal==null){
			//	We were editing a new deal so add it and show it
		}else{
			//	save the deal, add it to the stack and rerender everything
		}
		scope.deals_list_view.enable();
		_new_deal=null;

		//	Show the last view!
		// scope.deals_edit_view.render_no_deals();
		rerender_edit_view(true);
	});
	
	scope.deals_edit_view.subscribe_to('on_save_deal_clicked',function(view_save_event){
		//	Save the deal!
		scope.deals_service.save_deal(view_save_event.deal,function(service_save_event){
			_selected_lookup={};							//	Empty the selected lokoup
			_selected=[service_save_event.id];				//	Set selected as the new deal
			_selected_lookup[service_save_event.id]=true;	//	Set the lookup flag for this deal
			// console.warn(_deals_lookup);
			_deals_lookup[service_save_event.id]=service_save_event;
			// view_save_event.deal
			// group_deal(service_save_event);
			// prepare_data();
			// 			// build_selected_indeces();
			// 			
			// 			scope.deals_list_view.enable();		//	re-enable the list view			// 
			// 			// _new_deal=service_save_event;
			// 			
			// 			// rerender_edit_view(true);		//	render the edit view with the new deal
			// 			update_views()
			
			prepare_data();
			scope.deals_list_view.enable();		//	re-enable the list view			// 
			update_views();
			
			var message = "Deal saved.";
            scope.message_service.show_message({
                message: message,
                type: "notification"
            });
		});
	});
	
	scope.deals_search_view.subscribe_to("on_search_term_changed",function(e){
		// _groups=null;
		_selected=[];
		_selected_lookup={};
		
		build_selected_indeces();
		load_data(e.term);

	});
	
	//	When th
	scope.deals_search_view.subscribe_to("on_search_term_empty",function(e){
		// _groups=null;
		_selected=[];
		_selected_lookup={};
		
		build_selected_indeces();
		load_data("");
	});
	
	scope.deals_list_view.subscribe_to('on_deals_filter_changed',function(e){
		// alert("asdasd");
		_filter_by=e.filter_by;
		// render_deals_list();
		// build_selected_indeces();
		prepare_data();
		
		update_views();
		// _filtered_list=prepare_list_data(_filter_by);
		//	When the filter changes, we need to work out if we have any items in this list selected
		
		// var _model=$.extend({},{groups:_filtered_list,filter_by:_filter_by},_deal_lookups);
		// scope.deals_list_view.render(_model);
		// rerender_edit_view();
	});

	scope.deals_edit_view.subscribe_to('on_delete_deal_clicked',function(e){
		__deal=[];
		$.each(_selected,function(i,n){
			__deal.push(_deals_lookup[n]);
		});
		
		console.info("Deleting deals .. ",__deal);
		
		scope.deals_service.delete_deal(__deal,function(deal){
			e.paint();
			_selected=[];
			prepare_data();
			update_views();
		});
	});
	
	scope.deals_edit_view.subscribe_to('on_reassign_deal_clicked',function(e){
		// alert("asdasd");
		__deal=[];
		$.each(_selected,function(i,n){
			__deal.push(_deals_lookup[n]);
		});
		
		// console.info("Reassigning deals .. ",__deal);
		
		// console.warn(e.user);
		
		scope.deals_service.reassign_deal(__deal,e.user.id,function(deal){
			// e.paint();
			// _selected=[];
			var message = __deal.length+" deals re-assigned.";
            scope.message_service.show_message({
                message: message,
                type: "feedback"
            });

			prepare_data();
			update_views();
		});
		
	});
	
	scope.deals_edit_view.subscribe_to('on_edit_clicked',function(e){
		_new_deal=_deals_lookup[_selected[0]];
		scope.deals_list_view.disable();
		
		//	Need to pass in the companies, contacts and users here!
		scope.deals_edit_view.edit({
			deal:_new_deal,users:_users_lookup
		});
	});

	scope.deals_edit_view.subscribe_to('on_status_change_clicked',function(e){
		// alert("asdasd");
		//	CHANGE THE STATUS!
		_deals_lookup[_selected[0]].status=(['IN_PROGRESS','WON','LOST'])[e.status];
		
		scope.deals_service.save_deal(_deals_lookup[_selected[0]],function(f){
			prepare_data();
			scope.deals_list_view.enable();		//	re-enable the list view			// 
			update_views()
		});
			// Is the deal in the current filter?
	});	
	
	scope.deals_edit_view.subscribe_to('on_edit_deal_canceled',function(e){
		scope.deals_edit_view.render(_deal,_lookups,_users_lookup);
		
		// scope.deals_edit_view.edit({model:[_deal]},_lookups,_users_lookup);
	});	
	
	// Adding notes and tasks to deals
	scope.deals_edit_view.subscribe_to('on_add_note_clicked',function(e){
		scope.notes_service.create_note_for_contact_and_deal(e.contact,_selected[0],e.body,function(f){
			// console.warn("New Note ",f);
			// e.update(f);
			rerender_edit_view();
		});
		// alert("Adding a note!");
	});
	
	scope.deals_edit_view.subscribe_to('on_delete_note',function(e){
	    scope.notes_service.delete_note(e.note_id,function(response){
          e.paint();
        });
	});
	
	scope.deals_edit_view.subscribe_to('on_edit_note',function(e){
	    scope.notes_service.save_note(e.note,function(response){
          e.paint();
        });
	});
	
	
	scope.deals_edit_view.subscribe_to('on_add_new_task',function(e){
		// alert(_selected);
		// scope.deals_edit_view.show_loading()
		e.task.deal=[""+_selected];
        scope.tasks_service.add_task(e.task,function(f){
            // e.paint(f);
			rerender_edit_view();
        });
	});
	
    scope.deals_edit_view.subscribe_to('on_task_complete_change',function(e){
         e.task.complete=(e.task.complete=="true")?"false":"true";
         scope.tasks_service.update_task(e.task,function(f){
             e.paint(f);
         });
    
     });
	
	function groups_by_filter(filter){
		var _groups_to_render=[];
		
	// alert((""+_filter_by)=="1");
		switch(""+_filter_by){
			case "0":_groups_to_render=[_groups[0]];break;
			case "1":_groups_to_render=[_groups[1]];break;
			case "2":_groups_to_render=[_groups[2]];break;
			default:_groups_to_render=_groups;break;
		}
		// console.warn(_groups_to_render);
		return _groups_to_render;
	}
	//	Methods that update views on a per view basis
	function render_deals_list(){
		// alert(_filter_by)
		var _groups_to_render=groups_by_filter(""+_filter_by);
	// console.l
		var _model=$.extend({},{
			deals_count:_deals.deals.length,
			groups:_groups_to_render,
			deals:_deals_lookup,
			selected_lookup:_selected_lookup
			});
		
		scope.deals_list_view.render(_model);
	}
	
	function render_edit_view(){

	}
	
	function group_deal(deal){
		//	ungroup it if it already exists!
		ungroup_deal(deal);

		var deals_group=null;

		switch(deal.status){
			case "IN_PROGRESS":deals_group=0;break;
			case "WON":deals_group=1;break;
			case "LOST":deals_group=2;break;
		}
		
		_deals_group_lookup[deal.id]=deals_group;
		
		_groups[deals_group].order.push(deal.id);
		_groups[deals_group].deals[deal.id]=deal;
		_groups[deals_group].deals_count++;
	}
	
	function ungroup_deal(deal){
		var deals_group=_deals_group_lookup[deal.id];
		if(deals_group!=null){
			_groups[deals_group].deals[deal.id]=null;
			delete _groups[deals_group].deals[deal.id];
			_groups[deals_group].deals_count--;
			_deals_group_lookup[deal.id]=null;
			delete _deals_group_lookup[deal.id];	
		}
	}
	
	function group_deals(){
		//	Sort the deals by order of name
		_groups[0].order=[];
		_groups[1].order=[];
		_groups[2].order=[];
		
		// 		
		var _deals_order=_deals.deals.sort(function(a,b){
			var deal_1=_deals_lookup[a.id];
			var deal_2=_deals_lookup[b.id];
			return ((deal_1.name).toLowerCase()<(deal_2.name).toLowerCase())?-1:1;
		});

		$.each(_deals_order,function(i,deal){
			group_deal(_deals_lookup[deal.id]);
		});
	}
	
	function prepare_list_data(filter_by){
		
	}
	
	function prepare_edit_data(groups,selected){
	}
	
	
	
	/*
		Methods thats are called on startup:
		1) Load the data
		2) Prepare the data
		3) Render the views
	*/
	
	/*
	*	Load all data needed at the start
	*/
	function load_data(q){
		scope.users_service.get_all_users_lookup(function(users){
			_users_lookup=users;
			//	Show loading for deals list!
			scope.deals_list_view.show_loading();
			
			if(q==null){q="";}
			
			scope.deals_service.get_deals_lookup(q,function(lookups,deals){
				
				var _delegates=[];
				_deals_lookup=lookups;
				_deals=deals;
				
				
				// _deals_contacts_lookup
				// _deals_companies_lookup
				$.each(_deals_lookup,function(i,n){
					// _delegates.push(function(e){
					// 						scope.deals_service.get_companies_lookup_for_deal(n.id,function(companies){
					// 							_deals_companies_lookup[n.id]=companies
					// 							e();
					// 						});
					// 					});
					// 				
					// 					_delegates.push(function(e){
					// 						scope.deals_service.get_contacts_lookup_for_deal(n.id,function(contacts){
					// 							_deals_contacts_lookup[n.id]=contacts;
					// 							e();
					// 						});
					// 					});
				});
				
				
				
				// Load task types
				_delegates.push(function(e){
					scope.tasks_service.get_task_types_lookiup(function(task_types){
						_task_types_lookup=task_types;
						e();
					});
				});
				

				Async.multi_thread_load(_delegates,function(){
					prepare_data();
					update_views();
				});
			});
		
		});
	}
	
	/**
	*	Prepares the initial load of data
	*/
	function prepare_data(){
		group_deals();
		build_selected_indeces();		
	}
	
	/**
	*	Update the list and edit view
	*/
	function update_views(){
		// scope.deals_list_view.render(models,_filter_by,_selected);
		// scope.deals_edit_view.render({model:[],user:_users_lookup});
		//	
		render_deals_list();
		rerender_edit_view();
		// var _model=$.extend({},{
		// 		groups:_filtered_list,
		// 		filter_by:_filter_by,
		// 		deals:_deals_lookup
		// 		});
		// 	scope.deals_list_view.render(_model);
	}
	
	
	//	Kick start by loading the data
	load_data();
}