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

/**
 *
 * @param scope
 */
function ContactVEController(scope){
  BaseController.call(this,scope);
    
    var _this = this;
    var contact;
    var _emails = null;
    var _telephones = null;
    var _websites = null;
    var _addressess = null;
    var _deals = null;
    
    scope.model.subscribe_to('model_changed',function(e){
		load_contact_data(e.model);
    });

    function load_contact_data(event){
            //contact=event;
            // Deep Copy!
            contact = $.extend(true,{},event);
            var req_count=0;
            var _notes=null;
            var _tasks=null;

			
            if (event.id)
            {
            Async.multi_thread_load([
                //  Load contact data
                function(callback){
                    scope.contacts_service.get_contact_by_id(contact.id, function(data){
                       contact = data;
                       callback();
                    });
                }
                //  Load all users
                ,function(callback){
                    scope.user_service.get_all_users(function(data){
                        scope.users_model.model(data);
                        callback();
                    });

                }//  Load tags
                ,function(callback){
                    scope.contacts_service.get_tags_for_contacts(contact.id,function(data){
                        contact.tag=data;
                        callback();
                    });
                }
            ]

            //  Handle all loaded
            ,function(){
                _this.raise_event('on_data_loaded',{});
                //  Tell its parent its loaded its data
            });
          }
          else
          {
//            contact = $.extend(contact,{tags:{tag:[]}});
//            _emails = new LinkedList((null!=contact.emailAddresses)?contact.emailAddresses.emailAddress:[]);
//            _telephones = new LinkedList((null!=contact.phoneNumbers)?contact.phoneNumbers.phoneNumber:[]);
//            _websites = new LinkedList((null!=contact.websites)?contact.websites.website:[]);
//            _addresses = new LinkedList((null!=contact.addresses)?contact.addresses.address:[]);
//            scope.view.render({contact:contact,
//              email_addresses:_emails,
//              telephones:_telephones,
//              websites:_websites,
//              addresses:_addresses},"edit");
          }





    };

    scope.view.subscribe_to('on_edit_contact_clicked',function(event){
      // _emails = new LinkedList((null!=contact.emailAddresses)?contact.emailAddresses.emailAddress:[]);
      // _telephones = new LinkedList((null!=contact.phoneNumbers)?contact.phoneNumbers.phoneNumber:[]);
      // _websites = new LinkedList((null!=contact.websites)?contact.websites.website:[]);
      // _addresses = new LinkedList((null!=contact.addresses)?contact.addresses.address:[]);
      // scope.view.render({contact:contact,
      //         email_addresses:_emails,
      //         telephones:_telephones,
      //         websites:_websites,
      //         addresses:_addresses},"edit");
      _this.raise_event('on_edit_contact_clicked',contact);
    });
    
    scope.view.subscribe_to('on_delete_contact_clicked',function(event){
      _this.raise_event('on_delete_contact_clicked',contact);
    });

    this.render_view=function(e){
     // _this.raise_event('on_data_loaded',{});
        scope.view.render({contact:contact},"view");
    };
    
    scope.view.subscribe_to('on_remove_email_clicked',function(event){
    });

    scope.view.subscribe_to('on_add_email_field_clicked',function(event){
          scope.contacts_service.new_email_address_for_contact(contact,function(e){
              var ee =_emails.new_list_item(e);
            contact.emailAddresses.emailAddress = _emails.serialise();
            event.show(ee);
        });
    });


    scope.view.subscribe_to('on_remove_phone_clicked',function(event){
        event.phone.remove();
        contact.phoneNumbers.phoneNumber = _telephones.serialise();
        event.remove(event);
    });

    // scope.view.subscribe_to('on_add_phone_field_clicked',function(event){
    //       scope.contacts_service.new_phonenumber_for_contact(contact,function(e){
    //           var ee =_telephones.new_list_item(e);
    //           contact.phoneNumbers.phoneNumber = _telephones.serialise();
    //           event.show(ee);
    //       });
    //   });


    scope.view.subscribe_to('on_remove_address_clicked',function(event){
        event.address.remove();
        contact.addresses.address = _addresses.serialise();
        event.remove(event);
    });

    // scope.view.subscribe_to('on_add_address_field_clicked',function(event){
    //     scope.contacts_service.new_address_for_contact(contact,function(e){
    //         var ee =_addresses.new_list_item(e);
    //         contact.addresses.address = _addresses.serialise();
    //         event.show(ee);
    //     });
    // });

    scope.view.subscribe_to('on_remove_website_clicked',function(event){
        event.website.remove();
        contact.websites.website = _websites.serialise();
        event.remove(event);
    });

    // scope.view.subscribe_to('on_add_website_field_clicked',function(event){
    // 
    //     scope.contacts_service.new_website_for_contact(contact,function(e){
    //         var ee =_websites.new_list_item(e);
    //         contact.websites.website = _websites.serialise();
    //         event.show(ee);
    //     });
    // });
    


   scope.view.subscribe_to('on_tag_term_changed',function(event){

       //   Build a list of tags the contact already has
       var _tag_exists={};
       if(contact.tag){
            $.each(contact.tag.tag,function(i,n){
                _tag_exists[n.label]=n;
            });

       }
        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){
					if(!_tag_exists[tag.label]){
                        tag_string+=tag.label+'\n';
                    }
                });
            }
            event.update_tags(tag_string);
        });
    });
    
   scope.view.subscribe_to('on_add_tag',function(e){
       //  Check it doesnt already exist in the list
       var tag={"label":e.tag};

       scope.contacts_service.add_tag_to_contact(e.contact,tag,function(eee){
           e.render(e.contact);
       });
   });

   scope.view.subscribe_to('on_remove_tag',function(e){
       scope.contacts_service.remove_tag_from_contact(e.contact,{id:e.index},function(eee){
           var newArray = [];
           $.each(e.contact.tag.tag,function(index,existingTag){
             if (existingTag.id!=e.index)
             {
               newArray.push(existingTag);
             }
           });
           e.contact.tag.tag = newArray;
           e.render(e.contact);
       });
   });

//    scope.contact_edit_view.subscribe_to('on_add_new_note',function(e){
//       scope.notes_service.create_note_for_contact(e.contact.id,e.body,function(ef){
//            if(ef!=null){
//                scope.contacts_model.add_note_to_contact(scope.selected_contacts_model.model(),ef);
//                scope.contact_edit_view.show_flash({
//                    message:"New note has been added to "+e.contact.firstName+" " +e.contact.lastName,
//                    type:'notification'
//                });
//            }
//            else{
//                 scope.contact_edit_view.show_flash({
//                    message:"Could not add this note to "+e.contact.firstName+" " +e.contact.lastName,
//                    type:'error'
//                });
//            }
//        })
//    });

    //  Add task code goes here
//	scope.contact_edit_view.subscribe_to('on_add_new_task',function(e){
//        var d=Date.parseExact(e.task.dueOn,'dd/MM/yyyy')
//        e.task.dueOn=d.toString("yyyy-MM-ddTHH:mm:ssZ");
//
//        scope.tasks_service.add_task(e.task,function(ef){
//            if(ef!=null){
//                scope.contacts_model.add_task_to_contact(scope.selected_contacts_model.model(),ef);
//                scope.contact_edit_view.show_flash({
//                    message:"New task has been added to "+e.contact.firstName+" " +e.contact.lastName,
//                    type:'notification'
//                });
//            }
//            else{
//                scope.contact_edit_view.show_flash({
//                    message:"Could not add this task to "+e.contact.firstName+" " +e.contact.lastName,
//                    type:'error'
//                });
//            }
//        });
//    });

//    scope.contact_edit_view.subscribe_to('on_task_checked',function(e){
//        var task=scope.contacts_model.contact(_current_contact_index).task[e.task];
//
//        task.complete=e.checked;
//        scope.tasks_service.update_task(task,function(ef){
//          load_contact_data({model:[_current_contact_index]});
//        });
//    });
//
//    //  On delete - delete from model/view
//    scope.contact_edit_view.subscribe_to('on_delete_contact_clicked',function(event){
//        scope.contacts_service.delete_contact(scope.contacts_model.contact(_current_contact_index),function(e){
//            scope.contacts_model.remove(scope.contacts_model.model(),_current_contact_index);
//        });
//    });
};