#!/usr/bin/ruby
require "appscript"
require "osax"
include Appscript

puts "running"

# set up appscript connection
itunes  = app('iTunes');
sa      = OSAX::ScriptingAddition.new("StandardAdditions")
sel     = itunes.selection.get

xml     = "FrontRowExportPlaylist.xml";

ids     = []

puts "got itunes connection"

# get IDs of selected tracks if they're shared
for track in sel
  con = track.container.container.get
  kind = con.kind.get
  if kind == :'shared_library'
    sharename = con.name.get.to_s
    id = track.persistent_ID.get.hex # change in 7.2?
#    puts id.class, id
    if (id < 0)
#      puts "correcting id"
#      puts id
      id = 2**64+id
#    else
#      puts "no need to invert"
    end
    ids.push(id.to_s(base=16).upcase)
  end
end

if ids.length > 0
#  puts ids
else
  puts "No shared tracks"
  exit
end

itunes = nil # remove iTunes connection

puts "got tracks"

# open temporary file and set up XML
xml_alias = sa.path_to('temp') # implicit "system domain" here, might be nice to change
xml_file  = xml_alias.to_s + xml

playlist_start = <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Playlists</key>
  <array>
    <dict>
      <key>Name</key>
      <string>Remote Playlist</string>
      <key>Playlist Items</key>
      <array>
EOF

playlist_end = <<EOF
      </array>
    </dict>
  </array>
  <key>Tracks</key>
  <dict/>
</dict>
</plist>
EOF

# open and write file
playlist = File.new(xml_file, "w")

playlist.puts playlist_start

ids.each {
  |id|
  playlist.puts "				<dict>"
  playlist.puts "					<key>Persistent ID</key>"
  playlist.puts "					<string>" + id + "</string>"  
  playlist.puts "				</dict>"
}

playlist.puts playlist_end

puts "written xml to "+xml_file

# now tell AppleScript to add the playlist

# I'd like to do this with pure Ruby too, but it doesn't work. Any 
# clues?

# xml_alias = MacTypes::Alias.path(xml_file) # get alias once file is created
# shares = itunes.sources.get
# shares.each {
#   |share|
#   name = share.name.get
#   if name.to_s == sharename
#     puts "executing share add"
#     share.add(xml_alias)
#   end
# }

# so instead...

script = <<EOF
osascript -e 'set sharename to "#{sharename}"

tell application "iTunes"
	activate
	set shares to every source where kind is shared library
	repeat with share in shares
		get name of share
		if name of share is sharename then
			set playlist_path to (path to "temp" from system domain) & "#{xml}" as string as alias
			add playlist_path to share
		end if
	end repeat
    display dialog "done"
end tell
'
EOF

puts script

exec script
