#!/usr/bin/env python

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

import os
import sys
import string
import urllib
import re
import time

try:
    # thekorn:
    # can someone explain this different imports?
    # the imports in the 'except:' block should always work!?
    # but I'm not a packaging hero ;)
    import connector as Connector
    import commandLine
    import config
    import utils
    import output
    import statistic
except:
    from bugHelper.commandLine import commandLine
    from launchpadbugs.lphelper import sort
    import launchpadbugs.connector as Connector
    import bugHelper.utils as utils
    import bugHelper.config as config
    import bugHelper.output as output
    import bugHelper.statistic as statistic
    from launchpadbugs.basebuglistfilter import URLBugListFilter
    from launchpadbugs.lpconstants import BASEURL, BUG, BUGLIST
        
        
def no_by_attribute(bug_cls, attribute, op, v):
    def _no_by_attribute(bug):
        try:
            a = getattr(bug, attribute)
        except AttributeError:
            bug = bug_cls(bug)
            a = getattr(bug, attribute)
        x = len(a)
        value = int(v)
        if op == "<":
            return x < value and bug
        if op == ">":
            return x > value and bug
        else:
            return x == value and bug
    return _no_by_attribute
    



def main():
    conf = config.Config("~/.bughelper/config")
    cl = commandLine()
    
    if cl.options.parsemode not in ("text","html"):
        cl.parser.print_usage()
        sys.exit(1)
    if cl.options.format == 'csv' and not cl.options.stats:
        print '''csv format is only useful for stats'''
        sys.exit(1)
    if cl.options.format == 'csv' and not cl.options.closed_bugs:
        print '''csv format isn't really useful if you don't include closed bugs'''
        sys.exit(1)
        
    Bug = Connector.ConnectBug(method=cl.options.parsemode)
    BugList = Connector.ConnectBugList(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:
        BugList.authentication=cookie
        Bug.authentication=cookie
        
    try:
        out = output.Output("bugnumbers",cl.options.format,cl.options.file)
    except output.StyleNotFound, e:
        print >> sys.stderr, e
        sys.exit(1)
    out.print_header()
    start = time.time()

    bug_filter = URLBugListFilter()
    
    #HACK!!
    # the text-interface of LP does not provide infos like status, importance etc.
    # in a bug-list. [..]
    # move this to the end of the functions-list?
    if cl.options.parsemode == "text":
        if cl.options.format != "numbers" or (cl.options.sort or cl.options.stats):
            from launchpadbugs.basebuglistfilter import get_current_task
            bug_filter.functions.append(lambda x: get_current_task(x, bug_filter.baseurl, Bug))    

    if not cl.options.url:
        if not cl.options.sourcepackage and not cl.options.product and not cl.options.distro:
            cl.parser.print_usage()
            sys.exit(1)
            
        if cl.options.sourcepackage and not cl.options.distro:
            cl.options.distro = BUGLIST.DEFAULT_DISTRO
        
        if cl.options.product:
            if cl.options.sourcepackage:
                print "defining product AND sourcepackage goes not make sense, \
as only distros can have sourcepackages"
                cl.parser.print_usage()
                sys.exit(1)
            cl.options.url = bug_filter("%s/%s/+bugs" %(BASEURL.BUG_NG, cl.options.product))
        elif cl.options.distro and not cl.options.sourcepackage:
            cl.options.url = \
                    bug_filter("%s/%s/+bugs" %(BASEURL.BUG_NG, cl.options.distro))
        elif cl.options.distro and cl.options.sourcepackage:
            cl.options.url = \
                    bug_filter("%s/%s/+source/%s/+bugs" %(BASEURL.BUG_NG,
                                cl.options.distro, cl.options.sourcepackage))
        else:
            cl.parser.print_usage()
            sys.exit(1)
    else:
        try:
            cl.options.url = bug_filter(cl.options.url)
        except ValueError, e:
            print >> sys.stderr, e
            sys.exit(1)
            
    if cl.options.ignore_conflicts:
        bug_filter._conflicts_error = bug_filter.ADD
         
    if cl.options.minbug:
        from launchpadbugs.basebuglistfilter import minbug
        bug_filter.functions.append(lambda x: minbug(x, int(cl.options.minbug)))
        
    if cl.options.filterbug:
        from launchpadbugs.basebuglistfilter import filterbug
        bug_filter.functions.append(lambda x: filterbug(x, map(int, cl.options.filterbug.split(","))))

    if cl.options.branch:
        if not cl.options.parsemode == "html":
            print "branch information is only accessible via --parsemode=html"
            sys.exit(1)
        else:
            from launchpadbugs.basebuglistfilter import hasbranch
            bug_filter.functions.append(lambda x: hasbranch(x, Bug))
        
    if cl.options.lastcomment:
        from launchpadbugs.basebuglistfilter import lastcomment
        from launchpadbugs.lptime import LPTime
        def _parse_lastcomment(a):
            ret_dict = {}    
            x = [i.strip() for i in re.split(r"([ |&]?)([du:]{2})", a) if i]
            ret_dict["operation"] = "|"
            if "&" in x:
                ret_dict["operation"] = "&"
                x.remove("&")
            x = [i for i in map(lambda a: not(a=="|" or a=="&") and a, x) if i]
            if len(x) == 1:
                x.insert(0, "u:")
            assert not(len(x) %2), "wrong number of arguments"
            for i in range(0,len(x),2):
                if x[i] == "u:":
                    ret_dict["user"] = x[i+1]
                elif x[i] == "d:":
                    try:
                        if x[i+1].startswith("="):
                            ret_dict["at"] = LPTime(x[i+1].lstrip("="))
                        elif x[i+1].startswith("<"):
                            ret_dict["before"] = LPTime(x[i+1].lstrip("<"))
                        else:
                            ret_dict["after"] = LPTime(x[i+1].lstrip(">"))
                    except ValueError, e:
                        print  >> sys.stderr, "%s, ignoring given date" %e
                else:
                    cl.parser.print_usage()
                    sys.exit(1)
            return ret_dict
        opt_d = _parse_lastcomment(cl.options.lastcomment)
        #print opt_d#DEBUG
        if "at" in opt_d.keys():
            if "before" in opt_d.keys() or "after" in opt_d.keys():
                raise TypeError, "'at' and 'after' or 'before' is not allowed"
        bug_filter.functions.append(lambda x: lastcomment(x, Bug, **opt_d))
        

    re_opt = re.compile('^(<|>){0,1}([0-9]+$)')
    opt_dict = {"no_duplicates": "duplicates", "no_subscribers": "subscribers",
                "no_comments": "comments", "no_attachments": "attachments"}
    for i,k in opt_dict.iteritems():
        x = getattr(cl.options, i)
        if x:
            m = re_opt.search(x)
            if not m:
                cl.parser.print_usage()
                sys.exit(1)
            bug_filter.functions.append(no_by_attribute(Bug, k, m.group(1), m.group(2)))
          
    if cl.options.status:
        x = set(cl.options.status.split(","))
        if not x <= set(BUG.STATUS.values()).union(set(BUG.STATUS_INCOMPLETE_ADD.values())):
            raise ValueError, "unknown status: %s" %x
        if "Incomplete" in x:
            x.remove("Incomplete")
            x = x.union(set(BUG.STATUS_INCOMPLETE_ADD.keys()))
        for k,i in BUG.STATUS_INCOMPLETE_ADD.iteritems():
            if i in x:
                x.remove(i)
                x.add(k)
        bug_filter.add_option("status", x)
        
    if cl.options.importance:
        x = cl.options.importance.split(",")
        if not set(x) <= set(BUG.IMPORTANCE.values()):
            raise ValueError, "unknown status: %s" %x
        bug_filter.add_option("importance", x)
        
    if cl.options.component:
        x = cl.options.component.split(",")
        if not set(x) <= set(BUGLIST.COMPONENT_DICT.keys()):
            raise ValueError, "unknown component: %s" %x
        bug_filter.add_option("component", x)
        
    if cl.options.closed_bugs:
        bug_filter.add_option("status", BUG.STATUS.values())
        
    if cl.options.tag:
        bug_filter.add_option("tag", cl.options.tag.split(","))
        
    if cl.options.duplicates:
        bug_filter.add_option("duplicates", ("off",))

    if cl.options.patch:
        bug_filter.add_option("has-patch", ("on",))
    
    if cl.options.needs_forwarding:
        bug_filter.add_option("upstream-status", ("pending_bugwatch",))

    if cl.options.fixed_upstream:
        bug_filter.add_option("upstream-status", ("resolved_upstream",))
        
    if cl.options.reporter:
        bug_filter.add_option("reporter", (cl.options.reporter,))
        
    #print "USING THIS URL, ", bug_filter.baseurl
    #sys.exit(1)

    try:
        bl = BugList(cl.options.url)
    except BugList.Error.LPUrlError, e:
        if cl.options.sourcepackage:
            print >> sys.stderr, "Maybe package '%s' does not exist in Ubuntu." % cl.options.sourcepackage
        else:
            print >> sys.stderr, "Error while parsing '%s': %s.%s" %(cl.options.url, e, x)
        for i in ("+assignedbugs","+commentedbugs","+reportedbugs","+subscribedbugs"):
            if i in cl.options.url.baseurl:
                print >> sys.stderr, "Error while parsing '%s': %s.%s" %(cl.options.url.baseurl, e, x)
                print >> sys.stderr, "Please try using \"--parsemode=html\"" 
                break
        else:
            print >> sys.stderr, "Error while parsing '%s': %s.%s" %(cl.options.url.baseurl, e, x)
        sys.exit(1)
        
    if cl.options.upstream and cl.options.sourcepackage:
            l = None
            try:
                l = BugList(bug_filter("%s/%s/+bugs" %(BASEURL.BUG_NG, cl.options.sourcepackage)))
            except BugList.Error.LPUrlError, e:
                print >> sys.stderr, "There is no product <%s> in launchpad.net" %cl.options.sourcepackage
            if l:
                bl += l
            
    if cl.options.sourcepackage:
        path = os.path.expanduser(os.path.join(conf.attachments_cache, 
                                               cl.options.sourcepackage))
        utils.remove_obsolete_attachments(path, bl)      
    
    if not bl:
        if not bug_filter.urlopt:
            out.info("There are currently no open bugs.")
        else:
            out.info("No results for search.")
        sys.exit(1)
    elif cl.options.count:
        for x in bl:
            try:
                comments = x.comments
            except AttributeError:
                b = Bug(x)
                comments = b.comments
            out.print_item({"bug" : x, "count" : len(comments)},"comments")
    elif cl.options.stats:
        out.print_item(statistic.summary(bl),"statistic")
    else:
        if cl.options.sort:
            x = bl.sort(cl.options.sort)
            for bi in x:
                out.print_item({"bug" :bi})
        else:
            for bi in bl:
                out.print_item({"bug" :bi})

    footer_opt = {}
    if cl.options.footer:
        o = list(cl.options.footer)
        if "s" in o:
            footer_opt["statistic"] = statistic.summary(bl)
        if "t" in o:
            footer_opt["time"] = {
                "time": time.strftime("%a, %d %b %Y %H:%M:%S %Z"),
                "duration" : "%i" %(time.time() - start)}
    out.print_footer(footer_opt)
        

if __name__ == "__main__":
    main()

