//  @import com.hedgehoglab.application.view.BaseView;
//  @import com.hedgehoglab.application.controller.BaseController;

//  @import com.hedgehoglab.solomon.service.UsersService;
//  @import com.hedgehoglab.solomon.service.TasksService;
//  @import com.hedgehoglab.solomon.service.ContactsService;
//  @import com.hedgehoglab.solomon.service.DealsService;
//	@import com.hedgehoglab.solomon.view.TaskListView;
	
//	@import com.hedgehoglab.ui.LabBox;
$(function(e){

    var _user_service=new UsersService();
    var _tasks_service=new TasksService({});
	var _contacts_service=new ContactsService({});
	var _deals_service=new DealsService({});

    var _tasks_view=new TaskListView({element:$('#contact-tasks')});
    //var _active_tasks_view=new TaskListView({element:$('.active-tasks')});.complete-tasks
    var _filter_tasks_view=new FilterTasksView({element:$(".filter-bar-pane")});
    //var _contacts_import_view = new ContactImportView();

	var _subscribe_to_calendarview=new SubscribeToCalendarView(
		{
			element:$('.filter-bar-pane'),action:$('#subscribe_action')
		}
	);
	
	

	
    var _tasks_list_controller=new TaskListController({
        tasks_service:_tasks_service,
        user_service:_user_service,
		contacts_service:_contacts_service,
		deals_service:_deals_service,
		
        tasks_view:_tasks_view,
        filter_tasks_view:_filter_tasks_view,
		subscribe_to_calendarview:_subscribe_to_calendarview
    });


    //alert("asdas");
});



function SubscribeToCalendarView(scope) {
	BaseView.call(this, scope);
	var _this = this;
	var _lab_box = new LabBox({width:700,height:275,buttons:['close']});	
	var _server_url="";
	
	scope.action.bind('click', function() {
       _this.raise_event('subscribed_clicked', {
			paint:function(data){
				_server_url=data.server_url;
				_this.render_template_with_view(
					"tasks/subscribe-to-calendar",
					data,
					_this,
					function(rendered_template){
						var element=$(rendered_template);
						
						$('#reset-hash-action',element).bind('click',function(e){_this.raise_event('new_ical_hash',{
								update:function(setting){
									var s=_this.resource_string('label.task.subscribetocalendar',_server_url,setting.value)
									$('#ical-url',element).html(s);
									$('#ical-url',element).attr('href',s);
								}
							})

							return false;
						});
						
						_lab_box.show(element[0],function(){});
					}
				);	
				
			}
		
		});
	
		
	    return false;
    });
	
};



function TaskListController(scope){
    BaseController.call(this,scope);
    var _filter={};
    var _users=null;
	var _contacts=null;
	var _deals_lookup = null;
	var _deals=null;
	
	var _contacts_lookup=null;
    var _user=null;
    var _task_types=null;
    var _active_tasks=null;
    var _complete_tasks=null;
    var _all_tasks=[];
    var _conc_tasks=[];


    //  Markers to help sync the task/tasks requests
    var _task_stamp={start:null,end:null};
    var _tasks_stamp={start:null,end:null};

    
    var _groups={
        //  TODO    -   define groups
    };

	// scope.subscribe_to_calendarview.subscribe_to('subscribed_clicked', function(event) {
	// 	alert('aasdasd');
	// });
	// 					// scope.import_view.show();

    scope.tasks_view.subscribe_to('on_task_checked',function(e){
        e.task.complete=(e.task.complete=="true")?"false":"true";

        _task_stamp.start=(new Date()).getTime();

        scope.tasks_service.update_task(e.task,function(f){
            $.each(_conc_tasks,function(i,n){
                if(n.id==f.id){

                    _conc_tasks[i]=f;
                }
            });
            e.paint();
            paint();
        });
    });

	scope.subscribe_to_calendarview.subscribe_to('new_ical_hash',function(reset_event){
		scope.user_service.get_current_user(function(user){
			scope.user_service.reset_user_setting(user.id,"calendar_hash",function(setting){
				reset_event.update(setting);
			});
		});
	});


	scope.subscribe_to_calendarview.subscribe_to('subscribed_clicked',function(subscribe_event){
		scope.user_service.get_current_user(function(user){
			scope.user_service.get_server_url(function(server_url){
				scope.user_service.get_user_setting(user.id,"calendar_hash",function(setting){
					subscribe_event.paint({
						server_url:server_url,
						hash:setting.value
					});
				});
			});
		});
		
	});
	
	
    scope.tasks_view.subscribe_to('on_task_updated',function(e){
        //e.task.complete=(e.task.complete=="true")?"false":"true";
        scope.tasks_service.update_task(e.task,function(f){
            //  Does it match the filter?
            //  If not, remove it
            $.each(_conc_tasks,function(i,n){
                if(n.id==f.id){
                    _conc_tasks[i]=f;
                }
            });
            e.paint(matchesfilter(f));
            paint();
        });
    });

    function matchesfilter(e){
		// var _match=true;
		// //	Assigned To
		// if(e.assignedTo!=_filter.user) _match=false;
		// 
		// //	Type
		// if((""+_filter.type)!="0"){
		// 	if((""+_filter.type)!=e.type) _match=false;
		// }
		// 
		// //	Date!
		// 

		return true;
    };

//
//
    function sort_tasks(tasks){
        _conc_tasks=_conc_tasks.sort(function(a,b){
            if(a.dueOn!=null && b.dueOn!=null){
                //  Todo, precalculate dates in another array, this is slow

                var _a=Date.parse(a.dueOn);
                var _b=Date.parse(b.dueOn);
                return _b.compareTo(_a);
            }else{
                //alert("No Date in a or b");
            }
        });

        return _conc_tasks;
    }
    function group_tasks(tasks){
        var t={
            "all":{},"complete":{},"active":{},complete_count:0,incomplete_count:0
        }

        $.each(tasks,function(i,n){
            t.all[n.id]=n;

            if("true"==n.complete){
                t.complete[n.id]=n;
				t.complete_count++;
            }else{
                t.active[n.id]=n;
				t.incomplete_count++;
            }
        });
        return t;    
    };

    //  Get the tasks using the filter
    function paint(data){
        var t=sort_tasks();
        _all_tasks=group_tasks(t);

        scope.tasks_view.render({
            users:_users,task_types:_task_types,groups:_groups,tasks:_all_tasks,contacts:_contacts
			,contacts_lookup:_contacts_lookup,deals_lookup:_deals_lookup,deals:_deals
        });
    }


    function update_tasks(e){
        _filter.complete=false;

        scope.tasks_service.get(_filter,function(e){
            _active_tasks=e;
            _filter.complete=true;
            scope.tasks_service.get(_filter,function(e){
                _complete_tasks=e;
                _tasks_stamp.start=(new Date()).getTime();

                  var t=new Array();
                    if(_complete_tasks){
                        t=t.concat(_complete_tasks.task);
                    }

                    if(_active_tasks){
                        t=t.concat(_active_tasks.task);
                    }
                    _conc_tasks=t;
                paint();


                //  To re-implement automatic update, the ajax requests need to be marshalled...
                //setTimeout(update_tasks,10000);
            });
        });
    }

	//	Functions to set dates for filter
    function do_all(){
        _filter.to_date=Date.today().addYears(1).clearTime().getTime();
        _filter.from_date=Date.today().addYears(-1).clearTime().getTime();
    }

    function do_overdue(){
        _filter.to_date=Date.today().clearTime().getTime();
        _filter.from_date=Date.today().addYears(-1).clearTime().getTime();;
    }

    function do_today(){
        _filter.to_date=Date.today().clearTime().addDays(2).addMinutes(-1).getTime();
        _filter.from_date=Date.today().clearTime().getTime();
    }

	function do_tomorrow(){
        _filter.to_date=Date.today().clearTime().addDays(3).addMinutes(-1).getTime();
        _filter.from_date=Date.today().clearTime().addDays(1).getTime();
    }

    function do_future(){
        _filter.to_date=Date.today().addYears(10).clearTime().getTime();;
        _filter.from_date=Date.today().clearTime().addDays(3).addMinutes(-1).getTime();
    }



	scope.filter_tasks_view.subscribe_to('on_subscribe_to_calendar',function(e){
		
	});
	
    scope.filter_tasks_view.subscribe_to('on_filter_changed',function(e){
        _filter=$.extend(_filter,e.filter);

        if(_filter.type=="-1") _filter.type=null;

        if(_filter.user=="-1") _filter.user=null;

        //  Work out what the values for the dates should be
        switch(_filter.date){
            case "0":do_all();break;
            case "1":do_overdue();break;
            case "2":do_today();break;
            case "3":do_tomorrow();break;
            case "4":do_future();break;
        }


        update_tasks();
		e.paint();
    });
    
    function get_service_data(_callback){
        
        scope.user_service.get_current_user(function(user){
            _user=user;
			scope.deals_service.get_deals_lookup("",function(lu,ca){
				_deals_lookup = lu;
				_deals = ca;
			
			
				scope.contacts_service.get_contacts_lookup(function(lu,ca){
	
					_contacts=ca;
					_contacts_lookup=lu;
					scope.tasks_service.get_task_types(function(task_types){
		                _task_types=task_types;
		                scope.user_service.get_all_users(function(users){
		                    _users=users;
		                    _groups=[
		                        {"title":"all"},
		                        {"title":"overdue"},
		                        {"title":"today"},
								{"title":"tomorrow"},
		                        {"title":"future"}
		                    ];

		                    _filter.user = user.id;
		                    do_all();
		                    _filter.complete = false;
		                    _filter.type = 0;

		                    _callback();

		                });
		            });
				});
			});
        });
    }

    //  Get the service data
    function main(e){
        get_service_data(function(service_data){

            scope.filter_tasks_view.render({
                user:_user,users:_users,task_types:_task_types,groups:_groups
            });
            update_tasks()
			
			//var interval=setInterval(update_tasks,10000);
        });

    };

    main();
};

function FilterTasksView(scope){
    BaseView.call(this,scope);
	ContactViewHelper.call(this,scope);
    var _this=this;
	// var _helpers=new _this.generate_helpers(this,[ContactViewHelper]);
    var _filter={};

    function change_filter(filter){
        _filter=$.extend(_filter,filter);
		
		setTimeout(function(e){scope.element.addClass('ajaxLoading');},1);

        _this.raise_event('on_filter_changed',{filter:_filter,paint:function(e){
			//
			setTimeout(function(e){scope.element.removeClass('ajaxLoading');},200);

			}
		});
    }

    //alert(scope.element.html());
    this.render=function(model){
	
		//	Add subscribe action
		$('.subscribe-action',scope.element).bind('click',function(e){
			// alert("asdasd");
			_this.raise_event('on_subscribe_to_calendar',{});
			return false;
        });
	
        //  Update the users select
        $("select[name='user']",scope.element).html("");
        //$("select[name='user']",scope.element).append('<option val="-1">all</option>');
		
        $.each(model.users.user, function(index,user){
            $("select[name='user']",scope.element).append('<option val="'+user.id+'"  '+((""+user.id==""+model.user.id)?'selected="selected"':"")+'>'+_this.user_fullname(user)+'</option>');
        });
        $("select[name='user']",scope.element).bind('change',function(e){
            var id=$($(this)[0].options[$(this)[0].selectedIndex]).attr('val');
            //alert(id);
            var filter={
                user:id
            };
            change_filter(filter);
        });


        $("select[name='type']",scope.element).html("");
        $("select[name='type']",scope.element).append('<option val="-1">all</option>');
        $.each(model.task_types.taskType, function(index,type){
            $("select[name='type']",scope.element).append('<option val="'+type.id+'">'+type.name+'</option>');
        });
        $("select[name='type']",scope.element).bind('change',function(e){
            var id=$($(this)[0].options[$(this)[0].selectedIndex]).attr('val');
            //alert(id);
            var filter={
                type:id
            };
            change_filter(filter);
        });

        $("select[name='date']",scope.element).html("");
        
        $.each(model.groups, function(index,group){
            $("select[name='date']",scope.element).append('<option val="'+index+'">'+group.title+'</option>');
        });
        $("select[name='date']",scope.element).bind('change',function(e){
            var id=$($(this)[0].options[$(this)[0].selectedIndex]).attr('val');
            //alert(id);
            var filter={
                date:id
            };
            change_filter(filter);
        });

		$('.reload-action',scope.element).bind('click',function(e){
            change_filter(_filter);
			return false;
        });
    };
};


function TaskItem(scope){
    //
    this.render=function(model){
        //  Check for changes and update view
    };
};