#!/usr/bin/python
#
# Author: Hugo Haas <hugo@larve.net>
# License: GPLv2

import sys
import getopt
from StoreCollection import StoreCollection
from CommandlineInterface import CommandlineInterface
from TextInterface import TextInterface
from GtkInterface import GtkInterface,GtkUnavailable
import Version
import os.path

def usage(exitcode = 0):
    print "picfolio-metadata %s" % Version.v
    print "(c) 2003-2004 Hugo Haas <hugo@larve.net>"
    print """
Usage:
  picfolio-metadata [options] <image name> <image name> ...

Options:
-f, --file=		specify the file where meta-data is stored
			(default: picfolio/picfolio.xml)
-t, --title=		specify the title for the object
-d, --description=	specify the description for the object
-g			graphical interface
-h, --help		this message
"""
    sys.exit(exitcode)

def main():
    args = sys.argv[1:]
    try:
        optlist, args = getopt.getopt(args, 'f:t:d:mgh',
                                      ["title=",
                                       "description=",
                                       "gtk",
                                       "help"])
    except getopt.error, msg:
        print >>sys.stderr, "ERROR: %s\n" % msg
        usage(2)
    cli = 0
    directory = 0
    has_title = 0
    has_desc = 0
    use_gtk = 0
    title = None
    description = None
    for o in optlist:
        name = o[0]
        value = o[1]
        if name in ('-f', '--file'):
            file = value
        elif name in ('-t', '--title'):
            cli = 1
            has_title = 1
            title = value
        elif name in ('-d', '--description'):
            cli = 1
            has_desc = 1
            description = value
        elif name in ('-g', '--gtk'):
            use_gtk = 1
        elif name in ('-h', '--help'):
            usage()
    files = [ ]
    for arg in args:
        if os.path.exists(arg):
            files.append(arg)
        else:
            print "ERROR: %s does not exist; removing from list" % arg
    stores = StoreCollection()
    if cli:
        ui = CommandlineInterface(stores)
        for arg in files:
            print "Arg: \"%s\""
            ui.enter_metadata(arg, has_title, title, has_desc, description)
    elif use_gtk:
        try:
            ui = GtkInterface(stores, files)
            # Not reached
            sys.exit(0)
        except GtkUnavailable:
            print "GTK not available"
            sys.exit(1)
    else:
        ui = TextInterface(stores)
        for arg in files:
            ui.enter_metadata(arg)
    stores.save(ui.info)
    sys.exit(0)

if __name__ == "__main__":
    main()
