//  @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.view.TaskListView;
	
$(function(e){
    var _user_service=new UsersService();
    var _tasks_service=new TasksService({});
	var _contacts_service=new ContactsService({});

    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 _tasks_list_controller=new TaskListController({
        tasks_service:_tasks_service,
        user_service:_user_service,
		contacts_service:_contacts_service,
		
        tasks_view:_tasks_view,
        filter_tasks_view:_filter_tasks_view
    });


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

function TaskListController(scope){
    BaseController.call(this,scope);
    var _filter={};
    var _users=null;
	var _contacts=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.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.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
			console.log(e.task);
            $.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!
		// 
		// console.log("FILTER",_filter);
		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
        });
    }


    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_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.contacts_service.get_contacts(function(contacts){
				_contacts=contacts;
				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);

		// console.log("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){
        //  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
    };
};