#!/usr/bin/ruby
#
# apply a iPhoto keyword using Ruby/ScriptingBridge.

require 'osx/cocoa'
include OSX
OSX.require_framework 'ScriptingBridge'

# utility AppleScript debugging method

# def dump( thingy )
#   puts thingy.to_s
#   ( thingy.class.objc_instance_methods - SBApplication.objc_instance_methods ).sort.each do |m|
#     puts " * #{ m }"
#   end
# end

# main code
iPhoto = SBApplication.applicationWithBundleIdentifier("com.apple.iPhoto")

# if we want all the iPhoto keywords:

# iphoto_keywords = iPhoto.keywords.arrayByApplyingSelector("name")

# build predicate and find a given named photo
filter = NSPredicate.predicateWithFormat("name == 'DSCF1295'")
photos = iPhoto.photos.filteredArrayUsingPredicate(filter)

photos.each do |photo|
#  puts photo.name
  
  # figure out what the keywords are
  # for now, we just try to apply the keyword anyway
#   tagged = false
#   photo_keywords = photo.keywords.arrayByApplyingSelector("name")
# 
#   if photo_keywords.containsObject("flickr")
#     tagged = true
#     photo_keywords.removeObject("flickr")
#     # remove it so that we can sync what's left with Flickr
#   end
#   puts ("   + '"+photo_keywords.componentsJoinedByString("', '")+"'") 
# 
#   # photo_keywords.delete("flickr") { tagged = false }
#   # puts ("   + '"+photo_keywords.join("', '")+"'") 
# 
#   puts ("   + and is tagged 'Flickr'? "+tagged.to_s.capitalize)
#   
#   if !tagged
#     puts ("    + need to tag");
    # iPhoto.activate
    photo.select
    photo.assignKeywordString("flickr")
#    exit
#  end
end

### roughly equivalent AppleScript (works)
# 
# tell application "iPhoto"
# 	activate
# 	set thePhotos to every photo whose name is "DSCF1295"
# 	repeat with thePhoto in every item of thePhotos
# 		select thePhoto
# 		set retval to assign keyword string "flickr"
# 	end repeat
# end tell
# 
# --tell application "Script Editor" to activate
