#!/usr/bin/env python

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

import sys

try: 
    from HTMLOperations import BugList, BugPage
    from commandLine import commandLine
    import utils as utils
except:
    from bugHelper.commandLine import commandLine
    from launchpadBugs.HTMLOperations import BugList, BugPage
    import launchpadBugs.utils as utils

def add_dict_value(dict, key):
    if not dict.has_key(key):
        dict[key] = 0
    dict[key] += 1
    return dict

def main():
    cl = commandLine()
    if not cl.options.url:
        if not cl.options.sourcepackage:
            cl.parser.print_usage()
            sys.exit(1)

        if cl.options.sourcepackage:
            cl.options.url = \
                "https://bugs.launchpad.net/distros/ubuntu/+source/%s/+bugs" % \
                cl.options.sourcepackage

        if not utils.package_exists(cl.options.sourcepackage):
            print "Package '%s' not found." % cl.options.sourcepackage
            sys.exit(1)

    bl = BugList(cl.options)
    all_bugs = bl.bugs

    if not all_bugs:
        print "No bugs found."
        sys.exit(1)
    elif cl.options.count:
        for x in all_bugs:
            oneBug = BugPage("https://bugs.launchpad.net/ubuntu/+bug/%s" % x)
            oneBug.countComments()
            print "https://bugs.launchpad.net/ubuntu/+bug/%s Comments %d" % (x, oneBug.comments)
    elif cl.options.stats:
        status = {}
        importance = {}
        for bi in all_bugs:
            status = add_dict_value(status, bi.status)
            importance = add_dict_value(importance, bi.importance)
        print "Total Bugs: %d" % len(all_bugs)
        print "Status: " , status
        print "Importance: ", importance
    else:
        for bi in all_bugs:
            print "%s (%s,%s) - %s" % (bi, bi.status, bi.importance, bi.summary)

if __name__ == "__main__":
    main()

