#!/usr/bin/env python

# Written by Henrik Nilsen Omma
# (C) Canonical, Ltd. Licensed under the GPL

import sys
import os

try: 
    import connector as Connector
    from commandLine import commandLine
    import utils as utils
except:
    from bugHelper.commandLine import commandLine
    import launchpadbugs.connector as Connector
    import launchpadbugs.utils as utils
    import bugHelper.config as config

def main():
    conf = config.Config("~/.bughelper/config")
    cl = commandLine()
    
    Bug = Connector.ConnectBug(method=cl.options.parsemode)
    cookie = cl.options.cookie
    if cookie:
        cookie = os.path.expanduser(cookie)
    else:
        try:
            cookie = os.path.expanduser(conf.cookie)
        except:
            if cl.options.debug:
                print >> sys.stderr, "No cookie-file found"
                
    if cookie:
        Bug.authentication=cookie
    
    if not len(cl.args) == 1:
        cl.parser.print_usage()
        sys.exit(1)

    try:
        nr = int(cl.args[0])
    except ValueError:
        print >> sys.stderr, "Error: given LP-bugnumber has to be an integer"
        cl.parser.print_usage()
        sys.exit(1)
    bug= Bug(nr)

    if cl.options.comments:
        comments = bug.comments
        print "Comments:", len(comments)
        print comments
    if cl.options.reporter:
        print bug.reporter
    if cl.options.title:
        print bug.title
    if cl.options.tags:
        print bug.tags
    if cl.options.countcomments:
        comments = bug.comments
        print len(comments)
    if cl.options.isduplicate:
        print "Duplicate of %s" % (bug.duplicate_of)
    if cl.options.comment or cl.options.lastcomment:
        comments = bug.comments
        cnr = -1 if cl.options.lastcomment else cl.options.comment
        comment = comments[int(cnr)]
        if comment:
            if cl.options.author:
                print comment.user
            if cl.options.date:
                print comment.date
            if not cl.options.author and not cl.options.date:
                print comment
        elif cl.options.verbose:
            text = ''
            for c in comments:
                text += c.number + ', '
            print "available comments: %s" % text


if __name__ == "__main__":
    main()

