import sys, os, cPickle, sre
from galleryProtocol import *

getenv = os.getenv

# A place to store temporary files (note: must be able to rm -rf it)
gTmpdir = "/tmp/galleryTmp"

# Album name is taken from environment unless it's set here
gAlbum = ""
#gAlbum  = "amaya-feb-2006"
#gAlbumPrettyName = "Amaya, Feb. 2006"

# This is only used if a new album is created
gAlbumParent = "amaya"

# Gallery location and credentials
gGallery = "http://www.n8gray.org/photos"
gLogin = "adminUser"
gPassword = "???"


def system(s):
    print s
    os.system(s)

def preflight():
    system("rm -rf " + gTmpdir)
    system("mkdir " + gTmpdir)

def perItem():
    os.chdir(gTmpdir)
    if getenv("iPImageIsMovie"):
        path = getenv("iPImageSourcePath")
        basename = os.path.basename(path)
        system("cp '%(path)s' '%(basename)s'" % locals())
    else:
        path = getenv("iPImagePath")
        basename = os.path.basename(path)
        # Resize and convert to sRGB colorspace
        system("sips -Z 1024 -m \"/System/Library/Colorsync/Profiles/sRGB Profile.icc\" --out '%(basename)s' '%(path)s'" % locals())
    
    # For each image file foo.jpg we dump all the metadata to foo.jpg.meta
    metafile = open(basename + ".meta", 'w')
    cPickle.dump( os.environ, metafile, -1 )
    metafile.close()
    
    system("echo '%(basename)s' >> manifest" % locals())

def postflight():
    os.chdir(gTmpdir)
    g = Gallery(gGallery)
    print "Logging in to " + gGallery + " as " + gLogin
    g.login(gLogin, gPassword)
    
    # Make the album if necessary
    if gAlbum == "":
        albumPrettyName = getenv( 'iPAlbumName' )
        album = sre.sub( '[^a-z0-9_]+', '-', albumPrettyName.lower() )
    else:
        album = gAlbum
        albumPrettyName = gAlbumPrettyName
    
    albums = g.fetchAlbums()
    hasAlbum = 0
    for a in albums:
        if a['name'] == album:
            hasAlbum = 1
            break
    
    if not hasAlbum:
        print "Creating album " + albumPrettyName + " (" + album + ")"
        g.newAlbum( gAlbumParent, album, albumPrettyName )
    
    for f in open("manifest").readlines():
        f = f[:-1]   # Strip the newline
        print "Sending " + f
        meta = open(f + ".meta")
        env = cPickle.load( meta )
        meta.close()
        g.addItem( album, f, env["iPImageCaption"], env["iPImageComments"] )
    
    system("open " + gGallery + "/" + album)
        

if getenv("iPPreflight"):
    preflight()
elif getenv("iPPostflight"):
    postflight()
else:
    perItem()
