#!/usr/bin/python

import os
import sys
import kimdaba_album
import flickr_post

def push_images(fake):
    album = kimdaba_album.parse(kimdaba_album.kimdaba_default_album())
    new_images = kimdaba_album.select_images(album, set(["flickr"]), set(["flickd"]))
    for img in new_images:
        imgkeys = set([f.get("value") for f in img.findall("options/option/value")])
        # expand group members
        imgkeys.update(kimdaba_album.expand_keyword_groups(album, imgkeys))
        # don't include flickr
        imgkeys -= set(["flickr"])
        ispublic = True
        isfriends = False
        isfamily = False
        if "friendsonly" in imgkeys:
            ispublic = False
            isfriends = True
            imgkeys -= set(["friendsonly"])
        if "familyonly" in imgkeys:
            ispublic = False
            isfamily = True
            imgkeys -= set(["familyonly"])
        # maybe include from_kimdaba?
        imgpath = os.path.join(album.findall("config")[0].get("imageDirectory"),
                               img.get("file"))
        imglabel = img.get("label")
        imgdesc = img.get("description")
        # flickr rotate is degrees clockwise
        # kimdaba rotation is degrees... and we'll have to test :-)
        imgrot = img.get("angle")
        
        # img.get yearFrom monthFrom dayFrom etc. too...
        flickr_post.upload_one(imgpath,
                               title=imglabel,
                               description=imgdesc,
                               tags=imgkeys,
                               public=ispublic, friends=isfriends, family=isfamily, 
                               fake=fake,
                               rotate=imgrot)
        # this is all self contained...
        if fake:
            print "not flickd'ing it"
            return
        kimdaba_album.add_keyword(img.get("md5sum"), "flickd")

# TODO: sync-back, somehow
# Protocol: anything tagged flickr gets pushed
#   *then* it gets tagged flickd on this side, so it doesn't
#   get pushed again...

if __name__ == "__main__":
    fake=False
    if "--fake" in sys.argv:
        fake=True
        sys.argv.remove("--fake")
    prog, verb = sys.argv
    if verb == "register":
        flickr_post.register()
    elif verb == "sync":
        push_images(fake)
    else:
        sys.exit("register, sync")