from appscript import *
from mactypes import *
import os
import getopt
import sys
import time
import Growl

notifier = Growl.GrowlNotifier("python", ["python"])
notifier.register()

def display(msg):
    name = os.path.basename(sys.argv[0]).replace(".py","")
    notifier.notify("python",name , msg)



def error(msg):
    print "ERROR: %s" % msg
    sys.exit(-1)

def mkAlbum(iphoto,album_name):
    print "Create Album '%s'" % album_name
    iphoto.new_album(name = album_name)
    refs = iphoto.albums()
    ref = refs[len(refs)-1]
    if ref.name() != album_name:
        print "Error Creating %s" % album_name
    return ref
 
def checkAlbum(iphoto,name):

    refs = iphoto.albums()
    hit = False 
    for ref in refs:
        if ref.name() == name:
            print "%s %s" % ( ref.name() , name ) 
            hit = True
            break
    return hit

 

def doJob(iphoto,job):        
    if checkAlbum(iphoto,job['album']):
        print "Skip %s" % ( job['album'] )
        display("Skip Album %s" % ( job['album'] ))
        return
    display("Import Album %s" % ( job['album'] ))
    
    album = mkAlbum(iphoto,job['album'])
    time.sleep(1)    
    #for file in job['files']:
    #    print "try add %s to iphoto instance" % file
    #    ref = iphoto.add(file, to=album)
    #    if ref is None:
    #        raise
        
    #for file in job['files']:
    #    print "try to make photo %s" % file
    #    photo = iphoto.make(new = k.photo , with_properties = { 
    #                                        k.image_path : file.path,
    #                                            k.class_: k.photo,
    #                                    })
    #for idx,file in enumerate(job['files']):
    #    a = iphoto.open(file)
    #    while True:
    #        if len(iphoto.albums['Last Import'].photos()):
    #            break
    #        time.sleep(0.1)
    #    try:
    #        iphoto.add(app.albums['Last Import'].photos, to=album)
    #    except:
    #        print "ERROR: Add %02i/%02i %s to %s" % ( idx + 1, len(job['files']) ,file.path , job['album'] )
    #    print "Add %02i/%02i %s to %s" % ( idx + 1, len(job['files']) ,file.path , job['album'] )
    a = iphoto.open((job['files']))
    cnt = 0
    while True:
        if len(iphoto.albums['Last Import'].photos()) == len(job['files']):
            break
        time.sleep(1)
        cnt = cnt +1
        display("Import %i Files" % len(job['files']))
        print "Wait %i %i" % ( len(iphoto.albums['Last Import'].photos()) , len(job['files']) )
        if cnt == 120:
            display("Import failed, accept current ?")
            input = raw_input("Accept Import ? (%i)  [Y/n] >" % len(job['files'])  )
            if input.lower() != 'n':
                break
            cnt = 0
    print "Add %s" % ( job['album'] ) 
    display("Done Album %s" % ( job['album']) )
    try:
        iphoto.add(app.albums['Last Import'].photos, to=album)
    except:
        print "ERROR: Add %s" % ( job['album'] ) 
 

def addSingleJob(jobs,do_dir):
    
    name = None
    tmp =  do_dir.split("/")
    while not name:
        name = tmp.pop()
        if not len(name):
            name = None
    
    tmp = name.replace("_"," ")
    name = str(" ").join(map ( lambda x : x.capitalize() , tmp.split(" ")))
            
    job = { 'album'  : name ,
            'files' : []
    }
    d = os.listdir(do_dir)
    for file in d:
        if file.lower().find("jpg")>-1:
            file = do_dir + "/" + file
            try:
                job['files'].append(Alias(unicode(file)))
            except:
                print "Cannot add %s" % file
    jobs.append(job)
    return jobs

def addMultiJob(jobs,do_dir):
    for root, dirs, files in os.walk(do_dir):
        job = { 'album'  : None ,
                'files' : []
            }
        if not len(files):
          continue
        for name in files:
            file = os.path.join(root, name)
            try:
                if file.lower().find("jpg")>-1:
                    job['files'].append(Alias(unicode(file)))
            except:
                print "Cannot add %s" % file
        data = root.split("/")
        if len(data)>1:
            tmp = data[len(data)-1].replace("_"," ")
            job['album'] = str(" ").join(map ( lambda x : x.capitalize() , tmp.split(" ")))
        else:
            job['artist'] = data[0].replace("_"," ") 
        if len(job['files']):        
            jobs.append(job)
            print "Add Job %s" % (job['album'])
    return jobs

def main():
    
    def cmp(a,b):
        return a[:8] > b[:8]
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "d:r", ["dir=", 'recursiv'])
    except:
        error("Parsing args")
    
    do_dir = None
    do_recursiv = False
    for o,a in opts:
        if o in ('-d','dir'):
            do_dir = unicode(a,"utf-8")
        if o in ('-r','recursiv'):
            do_recursiv = True

    if not do_dir:
        error("No dir set")

    jobs = []
    if do_recursiv:
        jobs = addMultiJob(jobs,do_dir)
    else:  
        jobs = addSingleJob(jobs,do_dir)
    iphoto = app('iPhoto')
    sorted_job = {}
    display("Process %i Jobs" % len(jobs))
    for job in jobs:
        sorted_job[ job['album'] ] = job
    keys = sorted_job.keys()
    keys.sort()
    for key in keys:
        doJob(iphoto,sorted_job[key])
    display("Done")

if __name__ == '__main__':
  main()
