/* Copyright 2009 Palm, Inc.  All rights reserved. */

var ParticipantsAssistant = Class.create({
	initialize: function(targetEventAttendees,targetEvent) {
		//Mojo.Log.info("participants-assistant:initialize");
		this.targetEventAttendees = targetEventAttendees;
		this.targetEvent = targetEvent;
	},
	
	renderOrganizer: function(organizerEntry) {
		var html = Mojo.View.render({object: organizerEntry, template: 'participants/participant-organizer'})
		this.controller.get('partv_organizer_div').update(html);
	},
	
  renderContact:function(email,index,response){
		var entry = {};
		//Mojo.Log.info('participants:renderContact');
		var attendee = this.targetEventAttendees.attendees[index];
   	if (response && response.record) {
			
			var peep = this.targetEventAttendees.attendees.find(function(person){
				if (person.email == email) {
					return true;
				}
			}, this);
			
			if (peep) {
				if (response.record.firstName && response.record.lastName) 
					entry.name = response.record.firstName + " " + response.record.lastName;
				else if (response.record.firstName) 
					entry.name = response.record.firstName;
				else if (response.record.lastName) 
					entry.name = response.record.lastName;
				else if (peep.name) 
					entry.name = attendee.name;
				else 
					entry.name = attendee.email;
				
				entry.picUrl = response.record.pictureLocSquare;
				entry.contactid = response.record.id;
			}
		} else {
			if(attendee.name)
				entry.name = attendee.name;
			else
				entry.name = attendee.email;
		}
		if(this.targetEvent.accountDomain !="eas")
			entry.status = attendee.status;
		//set the picture for the contact
		if (!entry.picUrl) {
			entry.picUrl = 'images/list-avatar-default.jpg';	
		}
		entry.email=email;
		var value = (typeof attendee.organizer == 'boolean')?attendee.organizer:parseInt(attendee.organizer);
		
		if (value) {
			// Do not add the organizer to the list, instead render the organizer separately
			this.organizer = entry;
			this.renderOrganizer(entry);
		} else {
			this.attendees.push(entry);
		}
		
		if(index == (this.targetEventAttendees.attendees.size()-1)) {
			//do this only if we have received all the responses.
			this.participantList.items = this.attendees;
			//Mojo.Log.info('renderContact:model changed! %j',this.attendees);
			this.controller.modelChanged(this.participantList);
					
		}
	},
	
	getContactInfo:function(){
		this.targetEventAttendees.attendees.each(function(attendee) {
			//get this contact information if it is present using a reverse contact lookup
			//by passing the email information
			index = this.targetEventAttendees.attendees.indexOf(attendee);
			if(attendee.email) {
				getContactsService().getContactDetail(this.renderContact.bind(this,attendee.email,index),attendee.email,this.controller);
			} else
				this.renderContact(attendee.email,index,null);
		}, this);
			
	},
	 
	setup: function() {
		
		this.appMenuModel= { visible:true, 
					label:$L('Calendar'), 
					items: [ Mojo.Menu.editItem,
							{label:$L('Preferences & Accounts'), command:Mojo.Menu.prefsCmd, disabled: true},
							{label:$L('Help'), command:Mojo.Menu.helpCmd, disabled:false}]
		  		   }
		
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, this.appMenuModel);

		//Mojo.Log.info("participants-assistant:setup %j",this.targetEventAttendees);
		// *** PARTICIPANT LIST ATTRS & MODEL
		this.participantAttributes= {
			itemTemplate: 'participants/listitem',
		}
	
		this.participantList= {
			items: []
		}
		
		this.attendees=[];
		
		// Render the header
		var html = Mojo.View.render({object: {eventSubject: this.targetEvent.subject,}, template: 'participants/participant_header'})
		this.controller.get('partv_header').update(html);
		
		// Render the count
		html = Mojo.View.render({object: {count: this.targetEventAttendees.attendees.size()}, template: 'participants/participant-count'})
		this.controller.get('partv_count_div').update(html);
		
		this.controller.setupWidget('partv_list',this.participantAttributes, this.participantList);
			
		if (this.targetEventAttendees) {
			//organizer: this.targetEventAttendees.organizer,
			//num: this.targetEventAttendees.count
			this.getContactInfo();
		}
		
		this.service = getCalendarService();
		
		this.menuModel = {
			visible:true,
			items: [
					{},
					{},
					{label:$L('Email participants'), icon:'compose', command:'mailParticipants'}
				   ]};
			
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.menuModel);
	}, 
	
	activate: function() {
		this.organizerTapHandler = this.handleOrganizerTap.bindAsEventListener(this);
		this.controller.get('partv_organizer_div').observe(Mojo.Event.tap, this.organizerTapHandler);
		this.listTapHandler = this.handleListTap.bindAsEventListener(this);
		this.controller.get('partv_list').observe(Mojo.Event.listTap, this.listTapHandler);
	},
	
	deactivate: function() {
		this.controller.get('partv_organizer_div').stopObserving(Mojo.Event.tap, this.organizerTapHandler);
		this.controller.get('partv_list').stopObserving(Mojo.Event.listTap, this.listTapHandler);
	},
	
	handleOrganizerTap: function(event) {
		event.item = this.organizer;
		
		this.handleListTap(event);
	},
	
	handleListTap : function(event){
		//Mojo.Log.info('participants:handleListTap %j', event.item);
		
		var contactinfo = event.item;
		
		if (contactinfo) {
			if (contactinfo.contactid) {
				
				Pseudocard.pushPseudocard(this.controller.stageController, {personId:contactinfo.contactid});
				
			} else {
				this.launchPseudoCard(contactinfo);
			}
		}	
	},
		
	handleCommand: function(event) {
		if(event.type == Mojo.Event.command) {
			if(event.command == 'mailParticipants') {
				this.handleMailParticipants();	
			}else if(event.command == Mojo.Menu.helpCmd){
				getAppManagerService().launchHelp(this.controller);
			}
		}
	},
	
	getEmailAcctCallback: function(response) {
		//Mojo.Log.info("********* getEmailAcctCallback %s", Object.toJSON(response));
		var messageBody = $L('Running late, on my way...');
		getAppManagerService().launchComposeMessage(this.controller, 
																								this.targetEvent.subject, 
																								this.targetEventAttendees.attendees, 
																								messageBody,
																								response.accountId);	
	},
	
	getEmailAcctFailureCallback: function(response) {
		//Mojo.Log.info("### getEmailAcctFailureCallback");
		var messageBody = $L('Running late, on my way...');
		getAppManagerService().launchComposeMessage(this.controller, 
																								this.targetEvent.subject, 
																								this.targetEventAttendees.attendees, 
																								messageBody
																								/*accountId is undefined so email will use default email account*/);	
	},
	
	handleMailParticipants:function(){
		//Mojo.Log.info("*** handleMailParticipants domain %s login %s", this.targetEvent.accountDomain, this.targetEvent.accountLogin);
		// Retrieve the email account id corresponding to the calendar event's
		// account so we can send email from correct account.  If no email account
		// exists for the calendar event's account, then the default account in email will
		// be used to send this message
		getCalendarService().getEmailAccountId(	this.controller, 
																						this.targetEvent.accountDomain, 
																						this.targetEvent.accountLogin,
																						this.getEmailAcctCallback.bind(this),
																						this.getEmailAcctFailureCallback.bind(this));
	},
    
	// *** SUBLAUNCHING CONTACT DETAILS
	launchContactDetails: function(contactId){
    var appArgs = {
        appId : 'com.palm.app.contacts',
        name: 'detail'
    }
    this.controller.stageController.pushScene(appArgs,{personId:contactId});
  },
	
	launchPseudoCard: function(attendee){
		var firstname = attendee.name;
		var lastname = "";
		var indexOfSpace = attendee.name.lastIndexOf(' ');
		if (indexOfSpace == -1) {
			// No space was found, so let the firstname equals the attendee's name
		} else {
			firstname = attendee.name.slice(0, indexOfSpace);
			lastname = attendee.name.slice(indexOfSpace+1);
		}
		
		var contact = {	firstName: firstname,
										lastName: lastname,
						        emailAddresses: [{
						          value: attendee.email
						        }]
            			};

   // var params = {launchType: "pseudo-card", contact:contact}
   // var appArgs = {
   //     appId : 'com.palm.app.contacts',
    //    name: 'detail'
   // }	
    //this.controller.stageController.pushScene(appArgs,{contact:contact});
    
    Pseudocard.pushPseudocard(this.controller.stageController,{contact: contact});
  },
	


	
});