#!/usr/bin/env python
# -*- coding: utf-8 -*-

#----------------------------------------------------------------------
# Authors:
#   Bruno Dilly
#
# Copyright (C) 2007 Authors
#
# Released under GNU GPL, read the file 'COPYING' for more information
# ----------------------------------------------------------------------

# sys -- System-specific parameters and functions
# This module provides access to some variables used or maintained 
# by the interpreter and to functions that interact strongly with 
# the interpreter.
import sys
# getopt -- Parser for command line options
# This module helps scripts to parse the command line arguments in sys.argv
import getopt

# imcgui -- The pygtk interface of indymediadesktop
from imcgui import *
import imclib

def publish(imc, arguments, optional):
    print "Publishing, wait a moment..."
    if imclib.publish(0, arguments, optional):
        print "Done!"
    else:
        print "Failed!"
# publish

def usage():
    """
    Prints usage information
    """
    prog = sys.argv[ 0 ]
    print "Usage:"
    print "  %s" %prog
    print "to use graphical interface, or:"
    print "  %s [options] imc language title author summary path_to_article" % prog
    print
    print "Options and arguments:"
    print "  -h or --help\t\t\t: print usage information"
    print "  --email <xxx@yyy.zzz>\t\t: publish the author's email"
    print "  --homepage <xxx://yyy.zzz>\t: publish the author's homepage"
    print "  --html\t\t\t: for publish articles in html"
    print "  --media-title <xxx>\t\t: title of the media to be published"
    print "  --media-comment <xxx>\t\t: title of the media to be published"
    print "  --media-file </xxx/yyy.zzz>\t: path to the media file"
    print
# usage()

def parse_opts(argv):
    """
    Parses command line options and return options
    """
    try:
        # gnu_getopt is like getopt(), but allow option and non-option
        # arguments to be intermixed
        opts, args = getopt.gnu_getopt( argv[1:],
            "h t: f: c:",
            [ "help", "html", "media-title=", "media-file=",
                "media-comment=", "email=", "homepage=" ] )
    except getopt.GetoptError:
        # print help information and exit
        usage()
        sys.exit(2)

    arguments, optional = imclib.get_information()
    imcList = imclib.get_imc_list()
    imcIndex = None

    for o, a in opts:
        if o in ( "-h", "--help" ):
            usage()
            sys.exit( 0 )
        elif o in ("--html"):
            optional["html"] = True
        elif o in ("--email"):
            optional["email"] = a
        elif o in ("--homepage"):
            optional["homepage"] = a
        elif o in ("-t", "--media-title"):
            optional["media_titles"].append(a)
        elif o in ("-f", "--media-file"):
            optional["media_files"].append(a)
        elif o in ("-c", "--media-comment"):
            optional["media_comments"].append(a)

    # Verify quantity of media titles and files
    if (len(optional["media_titles"]) < len(optional["media_files"])) or (len(optional["media_titles"]) < len(optional["media_comments"])):
        print "Error: missing media titles"
        print "For help use --help"
        sys.exit(2)
    elif (len(optional["media_files"]) < len(optional["media_titles"])) or (len(optional["media_files"]) < len(optional["media_comments"])):
        print "Error: missing media files"
        print "For help use --help"
        sys.exit(2)
    elif (len(optional["media_comments"]) < len(optional["media_titles"])) or (len(optional["media_comments"]) < len(optional["media_files"])):
        print "Error: missing media comments"
        print "For help use --help"
        sys.exit(2)

    # If the user doesn't input arguments, it should call the graphical
    # interface (i.e. newbie mode)
    if len(args) == 0:
        graphical = True
    # If the number of arguments is right, it try to submit the data
    elif len(args) == 6:
        graphical = False
        #FIXME
        imcIndex = 0
        #imcIndex  = args[0]
        langIndex = -1
        for lang in imcList[imcIndex][3]:
            langIndex = langIndex + 1
            if lang[0] == args[1]:
                print "achei"
                break
        arguments["language"] = imcList[imcIndex][3][langIndex][1]
        print args[0], args[1], langIndex, imcList[imcIndex][3][langIndex][1]
        arguments["title"] = args[2]
        arguments["author"] = args[3]
        arguments["summary"] = args[4]
        arguments["article"] = open(args[5]).read()
    # Something is missing or exceeding
    else:
        print "The number of arguments is wrong."
        usage()
        sys.exit(2)
    return graphical, optional, arguments, imcIndex
# parse_opts()

def main(argv):
    """
    Gets the arguments and options, if any, and parse then, publishing it or
    calling the gtk gui.
    """
    graphical, optional, arguments, imcIndex = parse_opts(argv)
    # uses graphical interface
    if graphical:
        interface = GUI()
        interface.main()
    # or publish the data given by the arguments and optional
    else:
         publish(imcIndex, arguments, optional)
# main()

# Python calls the main function if the script starts running
if __name__ == '__main__':
    main(sys.argv)
