//  @import com.hedgehoglab.application.controller.BaseController;
//  @import com.hedgehoglab.solomon.model.ContactModel;

/**
 *
 * @param scope
 */
function ContactDealsController(scope){
  BaseController.call(this,scope);
  var _this = this;
  var _deals=null;
  var _grouped_deals=null;
  var _model=null;
  //  
  //  
   _this.render_view = function(){
       scope.view.render(_grouped_deals);
     };
  //  
   scope.model.subscribe_to('model_changed',function(e){
       _model = e.model;
       load_data(_model);
   });
  //  
   load_data = function(model){
       Async.multi_thread_load([
            //load deals for contact
             function(callback){
                 scope.contacts_service.get_deals_for_contact(model.id,function(data){
                     if(data==null){
                       data = null;  
                       _deals = data;
                     }else{
                         _deals = data;
                         data = group_deals(data);   
                     }
                    _grouped_deals=data;
                    callback(); 
                 });
             }
       ]
       //  Handle all loaded
       ,function(){
           _this.raise_event('on_data_loaded',{});
           //  Tell its parent its loaded its data
       });
       
   };
   
   
   function group_deals(data){
       var grouped = {'IN_PROGRESS':{'key':'In Progress','data':[]},'WON':{'key':'Won','data':[]},'LOST':{'key':'Lost','data':[]}};
		$.each(data.deal,function(i,deal){
		    switch(deal.status){
		        case 'IN_PROGRESS':grouped.IN_PROGRESS.data.push(deal); break;
		        case 'WON':grouped.WON.data.push(deal); break;
		        case 'LOST':grouped.LOST.data.push(deal); break;
		    }
		});
		return grouped;
	};
	
	_this.in_deals = function(deal_id){
	    var t=false;
	    if(_deals !=null){
	        $.each(_deals.deal,function(i,n){
	            if(n.id == deal_id && t==false){
	                t=true; 
                }
        	});
        	return t;
	    }
	    return t;
	};
	
	_this.add_deal = function(d){
	    if(_deals == null) _deals = {deal:[]};
	    _deals.deal.push(d);
	    _grouped_deals = group_deals(_deals);
	}
};