/**
*	@author	hedgehoglab
*/

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

function ContactDetailController(scope) {
    BaseController.call(this, scope);
    var _current_contact_index = null;
    var _this = this;
    var _event = null;


    //  Code to bottle neck view rendering until both smaller views have rendered
    var _child_controller_count = 0;

    function reset_controller_count() {_child_controller_count = 0;};

    function check_child_controller_count() {
        _child_controller_count++;
		//	When both views are prepared to render, render them
		// alert("BOTH LOADED")
        if (_child_controller_count == 2) {
			scope.contact_detail_view.render(_event,function(e) {
				scope.contact_VE_controller.render_view();
				scope.contact_NT_controller.render_view();
				try{
					if(e) e();
				}catch(e){
					// alert(e);
				}

				scope.contact_detail_view.hide_loading();
			});

			reset_controller_count();
		}
    };

    scope.contact_VE_controller.subscribe_to('on_data_loaded',check_child_controller_count);
    scope.contact_NT_controller.subscribe_to('on_data_loaded',check_child_controller_count);

    //  TODO - Refactor into own controller as its not part of this controller remit
    //  Load all types
    Async.multi_thread_load(
    [
    //  Load email types
    function(callback) {
        scope.contacts_service.get_email_types(function(e) {
            scope.general_types_model.set_email_types(e);
            callback();
        });
    }
    //  Load telephone types
    ,
    function(callback) {
        scope.contacts_service.get_phone_types(function(e) {
            scope.general_types_model.set_telephone_types(e);
            callback();
        });
    }
    //  Load address types
    ,
    function(callback) {
        scope.contacts_service.get_address_types(function(e) {
            scope.general_types_model.set_address_types(e);
            callback();
        });
    }
    //  Load website types
    ,
    function(callback) {
        scope.contacts_service.get_website_types(function(e) {
            scope.general_types_model.set_website_types(e);

            callback();
        });
    }
    //  Load IM types
    ,
    function(callback) {

        callback();
    }
    //  Load task types
    ,
    function(callback) {
        scope.tasks_service.get_task_types(function(e) {
            scope.general_types_model.set_task_types(e);

            callback();
        });
    }
    ]
    ,
    function(e) {
        //  Flag goes here to check for everything
		
        }
    );


	//	This is the problem with regards to the chosen 

	
	scope.contacts_list_view.subscribe_to('on_selected_contacts_changed',function(event){
		// alert("asdasd")
        reset_controller_count();
		scope.contact_detail_view.show_loading();
		
		_event = {model: event.model};	//	Wrap the event model in an event object;
		
		if ( event.model.length > 1 ){

			scope.selected_contacts_model.model(event.model);
        }else if (event.model[0] == -1){
			// alert("ITS A NEW CONTACT")
			// scope.contacts_service.empty_contact(function(empty) {
			// 				scope.contact_edit_controller.show_view(empty,function(e){
			// 					scope.contact_detail_view.hide_loading();
			// 					if(e) e();
			// 				});
			// 			});
        }
        else if (event.model.length == 1)
        {

			var t = scope.contacts_model.model().contact[event.model[0]];
			scope.selected_contacts_model.model(event.model);
        }
        else
        {
			scope.selected_contacts_model.model([]);
			// scope.contact_detail_view.render({
			// 			model: []
			// 			},function(e){
			// 				scope.contact_detail_view.hide_loading();
			// 			});
        }
		
        return false;
    });
    


	scope.selected_contacts_model.subscribe_to('model_changed',function(event) {
		if ( event.model.length != 0 && event.model[0] != -1){
			var _contacts = [],index;
			var _tag_count=event.model.length;
			
   			var selected=[];
			_event = {model: _contacts,selected:selected};
		
   			for (index = 0; index < event.model.length; index++) {
   				_contacts[index] = scope.contact_model.model().contact[event.model[index]];
   				selected.push(_contacts[index].id);
   				if (event.model.length <= 6){
					new (function(contact){
						scope.contacts_service.get_tags_for_contact(contact.id,function(tags){
							contact.tag =tags;
							_tag_count--;
							if(_tag_count==0){
								if( event.model.length == 1) scope.current_contact.model(_contacts[0]);
								scope.contact_detail_view.render(_event,function(e){
									
									//alert("RENDERING WITH TAGS");
									// alert(e);
									try{
										if(e) e();
									}catch(e){
										// alert(e);
									}
									
									// scope.contact_detail_view.hide_loading();
								});								
							}
						});						
					})(_contacts[index]);

				}else{
					new (function(contact){
						_tag_count--;
						if(_tag_count==0){
							if( event.model.length == 1) scope.current_contact.model(_contacts[0]);							
							scope.contact_detail_view.render(_event,function(e){
								
								// try{
									if(e) e();
								// }catch(e){
									// alert(e);
								// }
								// scope.contact_detail_view.hide_loading();
							});								
						}
					})(_contacts[index]);
				}
   			}
   			

        }else if (event.model[0] == -1){
			// 	
			scope.contacts_service.empty_contact(function(empty) {
				scope.contact_edit_controller.show_view(empty,function(e){
					scope.contact_detail_view.hide_loading();
					// if(e) e();
				});
			});
        }
        else if (event.model.length == 1){

			// scope.contact_detail_view.show_loading();
			// 		var t = scope.contacts_model.model().contact[event.model[0]];
			// 		scope.current_contact.model(t);
			// 		
			// 		scope.contact_detail_view.render([{model:t},function(e){
			// 			scope.contact_detail_view.hide_loading();
			// 			if(e) e();
			// 		});
			// scope.contact_edit_controller.show_view(t,function(e){
			// 	scope.contact_detail_view.hide_loading();
			// 	if(e) e();
			// });
        }
        else
        {
			scope.contact_detail_view.render({
			model: []
			},function(e){
				scope.contact_detail_view.hide_loading();
			});
        }
    });

	//	???????
    scope.selected_contacts_model.subscribe_to('model_updated',function(event){});
    scope.selected_contacts_model.subscribe_to('contact_changed',function(event) {});
    scope.current_contact.subscribe_to('model_changed',function(event) {});

    /*
        EVERYTHING TAG RELATED
    */

    scope.contact_detail_view.subscribe_to('on_tag_contacts_clicked',function(event) {
        var dels = [];
        
		$.each(scope.selected_contacts_model.model(),function(i, n) {
            var con = scope.contacts_model.model().contact[n];

            dels.push(function(e) {
                var tag = {
                    "label": event.tag
                };
                scope.contacts_service.add_tag_to_contact(con, tag,
                function(eee) {
                    e();
                });
            });
        });

        Async.multi_thread_load(dels,function(e) {
            var message = dels.length + " contact" + ((dels.length > 1) ? "s": "") + " tagged with '" + event.tag + "'.";
            scope.message_service.show_message({
                message: message,
                type: "info"
            });
            event.update();
        });
    });


    scope.contact_detail_view.subscribe_to('on_tag_term_changed',function(event) {
		// alert("ASDS")
        scope.tag_service.get_tags_by_search_term(event.term,
        function(tag_data) {
            var tag_string = "";
            if (tag_data) {
                $.each(tag_data.tag,
                function(index, tag) {
                    //  Dont allow tags that already exists
                    tag_string += tag.label + "\n";
                });
            }
            event.update_tags(tag_string);
        });
    });

    scope.contact_detail_view.subscribe_to('on_tag_remove_clicked',function(event) {

        scope.contacts_service.remove_tag_from_contact(event.contact, {
            id: event.tag_id
        },
        function(e) {
            event.update();
        });
    });

    scope.contact_detail_view.subscribe_to('on_delete_contacts_clicked',function(event) {

        scope.delete_dialog_view.show(event);
        scope.delete_dialog_controller.unsubscribe_to('on_confirm_clicked');
        var toDelete = [];

        scope.delete_dialog_controller.subscribe_to('on_confirm_clicked',function() {
			scope.contacts_service.delete_contact(event,function(e){
				scope.contacts_model.model(scope.contacts_model.model());
				scope.search_view.repeat_search();				
				scope.contacts_list_view.raise_event('on_selected_contacts_changed',{model:[]});


				 var message = event.length + " contact" + ((event.length > 1) ? "s": "") + " deleted.";
                scope.message_service.show_message({
                    message: message,
                    type: "info"
                });
			});
            return false;
        });
    });
	
	//	Real Call
    scope.contact_VE_controller.subscribe_to('on_delete_contact_clicked',function(event) {
        scope.delete_dialog_view.show(event);
        scope.delete_dialog_controller.unsubscribe_to('on_confirm_clicked');
        scope.delete_dialog_controller.subscribe_to('on_confirm_clicked',
        function() {
            index_to_delete = -1;
            name_deleted = event.firstName + " " + event.lastName;
            $.each(scope.contacts_model.model().contact,
            function(i, n) {
                if (n.id == event.id) index_to_delete = i
            });
            if (index_to_delete > -1)
            {
                scope.contacts_service.delete_contact(event,
                function(e) {
                    scope.contacts_model.remove(scope.contacts_model.model(), index_to_delete);

					// scope.selected_contacts_model.model([]);
					scope.contacts_list_view.raise_event('on_selected_contacts_changed',{model:[]});
					scope.contacts_model.model(scope.contacts_model.model());
					// scope.search_view.raise_event("on_search_term_changed", {term:''});
                    // scope.selected_contacts_model.model([]);
                    scope.message_service.show_message({
                        message: name_deleted + " deleted",
                        type: "info"
                    });
                });
            }
        });
    });

    scope.contact_VE_controller.subscribe_to('on_edit_contact_clicked',function(event) {
		scope.contact_edit_controller.show_view(event,function(e){
			e();
		});
    });

	//     scope.contact_detail_view.subscribe_to('on_save_contact',function(event) {
	// // alert("asdasd");
	//         _this.raise_event('on_save_contact',event);
	//     });

    // scope.contact_edit_controller.subscribe_to('on_cancel_edit_contact',function(event) {
    //     scope.selected_contacts_model.model(scope.selected_contacts_model.model());
    // });

    scope.contact_edit_controller.subscribe_to('on_update_contact',function(event) {
	 		_event={model:event};
			
			var ccc= scope.contacts_model.contact_by_id(event.id);
			if(ccc!=null) scope.contacts_model.contact_by_id(event.id,event);

			var temp = scope.contacts_model.model();
			if(ccc==null){
				//	It obviously doesnt exist so! we need to add it
				
				temp.contact.push(event);
				//	Sort and save
				temp.contact = temp.contact.sort(function(a,b){
					var a_name=((a.lastName!=null)?a.lastName:"")+((a.firstName!=null)?a.firstName:"")
					var b_name=((b.lastName!=null)?b.lastName:"")+((b.firstName!=null)?b.firstName:"")
					return a_name.toLowerCase()>b_name.toLowerCase();
				});
				scope.contacts_model.model(temp,true);
			}
			
			//Get index of selected and select
			$.each(scope.contacts_model.model().contact,function(i, n) {
				if (n.id == event.id)
				{
				    index = i;
				}
			});
			
			scope.contacts_list_view.raise_event('on_selected_contacts_changed',{model:[index]});
			scope.contacts_model.model(temp);
    });


    // scope.contact_edit_controller.subscribe_to('on_save_new_contact',function(event) {
    scope.contact_edit_controller.subscribe_to('on_save_contact',function(event) {
	//	alert("asdasd");

		if(event && event.error){
			var message = event.error;
            scope.message_service.show_message({
                message: message,
                type: "error"
            });
			scope.search_view.repeat_search();
			scope.contacts_list_view.raise_event('on_selected_contacts_changed',{model:[]});
			
		}else{
			_event={model:event};
			//	Do a check here for the licecn
			var ccc= scope.contacts_model.contact_by_id(event.id);
			if(ccc!=null) scope.contacts_model.contact_by_id(event.id,event);
			var temp = scope.contacts_model.model();

			if(ccc==null){
				//	It obviously doesnt exist so! we need to add it
				temp.contact.push(event);
				//	Sort and save
				// temp.contact = temp.contact.sort(function(a,b){
				// 					var a_name=((a.lastName!=null)?a.lastName:"")+((a.firstName!=null)?a.firstName:"")
				// 					var b_name=((b.lastName!=null)?b.lastName:"")+((b.firstName!=null)?b.firstName:"")
				// 					return a_name.toLowerCase()>b_name.toLowerCase();
				// 				});
				scope.contacts_model.model(temp,true);
			}

			//Get index of selected and select
			$.each(scope.contacts_model.model().contact,function(i, n) {
				if (n.id == event.id)
				{
				    index = i;
				}
			});

			scope.contacts_list_view.raise_event('on_selected_contacts_changed',{model:[index]});
			scope.contacts_model.model(temp);
		}
		
		
		// scope.selected_contacts_model.model([index]);
        
    });

    scope.contact_edit_controller.subscribe_to('on_cancel_new_contact',function(event) {
        scope.selected_contacts_model.model([]);
    });

	scope.contact_detail_view.subscribe_to('on_merge_contacts_clicked',function(event) {
		
		var toMerge = [];
		toMerge.push(event.destination);
		
		$.each(event.contacts,function(i, n) {
			if (n.id!=event.destination) toMerge.push(n.id);
		});
		
		scope.contacts_service.merge_contacts(toMerge,function(server_result) {
			scope.contacts_service.get_contact_by_id(server_result.id,function(merged_contact){
				console.info("Contacts Merged as ",merged_contact);
				$.each(toMerge,function(index, contact_id) {
					index_to_delete = -1;
		
					if((""+event.destination)!=(""+contact_id)){
						$.each(scope.contacts_model.model().contact,function(i, n) {
						    if (n.id == contact_id) index_to_delete = i;
						});
					}

					if (index_to_delete > -1)
					{
					    scope.contacts_model.remove(scope.contacts_model.model(), index_to_delete);
					}
				});
			
				scope.contacts_model.contact_by_id(server_result.id,merged_contact);
			
				$.each(scope.contacts_model.model().contact,function(i, n) {
					if (n.id == server_result.id)
					{
					    index = i;
					}
				});

				scope.contacts_list_view.raise_event('on_selected_contacts_changed',{model:[index]});
				scope.contacts_model.model(scope.contacts_model.model());
				
			});
        });
    });
};