#
#  MailSyncer.rb
#  RubyFrictionless
#
#  Created by Pierce T. Wetter III on 3/4/08.
#  Copyright (c) 2008 __MyCompanyName__. All rights reserved.
#

require 'email_template'

OSX.require_framework 'ScriptingBridge'
OSX.require_framework 'AddressBook'

class MailSyncer < OSX::NSObject

  def MailSyncer.singleton
     @@msyncer ||= MailSyncer.alloc.init 
  end
  
  @@bestEmail=nil
  def myEmailAddress
    return @@bestEmail if @@bestEmail
	myself = ABAddressBook.sharedAddressBook.me
	emailAddresses=myself.valueForProperty("Email")
	@@bestEmail = emailAddresses.valueAtIndex(emailAddresses.indexForIdentifier(emailAddresses.primaryIdentifier))
    @@bestEmail
  end

  def sendMail(to,subject,text)
    SBSendEmail.sendEmailMessageFrom_to_subject_content_send(myEmailAddress,to,subject,text,true)
  end
  
  def sendDelegateMail(to,action,extraText,delay)
	template= Email_Template.new
	subject= "TODO: "+ action.name
	subject << " > #{action.parent.name}" if action.parent?
	subject << " @#{action.context.name}" if action.context?
	if (action.isImportant? && action.isUrgent?)
		subject << " :ui"
	elsif (action.isImportant?)
		subject << " :i"
	elsif (action.isUrgent?)
		subject << " :u"
    end
	
	email=sendMail(to,subject,template.emailtext(action,extraText,delay))
	 if email then
		print "sent #{email.messageId}"
		action.outMailMessageID=email.messageId
	 end
  end
	
 def sendDoneMail(action,msg)
    @mail = SBApplication.applicationWithBundleIdentifier('com.apple.Mail') unless @mail
	return unless @mail
	return unless action.inMailMessageID
	outMsg = msg.replyOpeningWindow_replyToAll(true,false)
	s= outMsg.subject
	s = s.sub("Re: TODO: ","DONE: ")
	s = s.sub("TODO: ","DONE: ")
	s = s.sub("Re: ","DONE: ")
	begin
	  outMsg.subject=s
	rescue
	end
  end
    
  def findPerson(email)
	ab = ABAddressBook.sharedAddressBook
	find = ABPerson.searchElementForProperty_label_key_value_comparison("Email",nil,nil,email,6) # kABEqualCaseInsensitive=6
	results=ab.recordsMatchingSearchElement(find)
	if (results && results.size > 0)
	  return results[0]
	end
	return nil
  end
  
  def mailboxNames
    @mail = SBApplication.applicationWithBundleIdentifier('com.apple.Mail') unless @mail
	mailboxes=@mail.mailboxes
	result = []
	mailboxes.each{ |m| result << m.name }
	result
  end
	
	
  def syncMail(moc)

    @mail = SBApplication.applicationWithBundleIdentifier('com.apple.Mail') unless @mail
	return unless @mail
	
	mailboxes=@mail.mailboxes

	defaultValues = NSUserDefaultsController.sharedUserDefaultsController.values
	in_mbox_name = MailPreferences.incomingMailbox
	out_mbox_name = MailPreferences.outgoingMailbox
	
	if (! in_mbox_name || in_mbox_name.length < 0 ) then
		alrt=NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat("Error syncing Mail. No incoming mailbox specified!","OK",nil,nil,"")
		alrt.runModal
		return
	end
	if (! out_mbox_name || out_mbox_name.length < 0 ) then
		alrt=NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat("Error syncing Mail. No outgoing mailbox specified!","OK",nil,nil,"")
		alrt.runModal
		return
	end
	
    in_mbox=mailboxes.objectWithName(in_mbox_name)
    out_mbox=mailboxes.objectWithName(out_mbox_name)
	
#	print in_mbox
#	print out_mbox
	
	newActions=[]

    in_mbox.messages.get.each do |m| 
#      print "#{m.messageId} #{m.subject}\n" 
#       print "#{m.content}"
      oldAction=moc.objectWithQuotedValue_forKey_entityNamed(m.messageId,"inMailMessageID","Action")
	  oldAction= oldAction[-1] if oldAction
      if oldAction then
        if oldAction.done? && out_mbox then
		    sendDoneMail(oldAction,m) if oldAction.inMailMessageID
			m.moveTo(out_mbox) 
			#m.replyOpeningWindow_replyToAll(true,true)
		end
	  else # see if we sent this out!
		begin
			reply=m.headers.objectWithName("In-Reply-To")
			oldAction=moc.objectWithQuotedValue_forKey_entityNamed(m.messageId,"outMailMessageID","Action")
			oldAction= oldAction[-1] if oldAction
			if oldAction then
				oldAction.done=1 
				m.moveTo(out_mbox) 
			end
		rescue
		    oldAction= nil
		end
	  end
	  if (!oldAction) then
	    print "building new aciton for m.subject\n"
        newAction= NSEntityDescription.insertNewObjectForEntityForName_inManagedObjectContext("Action",moc)
		
        newAction.smartName= m.subject.sub("TODO: ",'')
        newAction.inMailMessageID=m.messageId
		newAction.delegatedFromEmail=m.sender;
		lookup = findPerson(newAction.delegatedFromEmail)
		newAction.delegatedFromID=lookup.uniqueId if lookup
		newAction.noteString = m.source
		#newAction.delegatedFrom = addressbook lookup m.sender
		newActions << newAction
      end
    end
	newActions
  end
  
end
