import os
import traceback
from trac.web.chrome import add_stylesheet

from trac.ticket.query import * 
from tram.util import debug
from trac.util.translation import _

class QueryModule(object):

    def process_request(self, req, projects):

        q = 'status=new|assigned|reopened'
        show_myticket = 0
        if not req.authname:
            req.authname = "anonymous"
        else:
            show_myticket = 1
            if req.args.get('myticket') == "true":
                q = 'status=new|assigned|reopened&owner=$USER'

        projs = []
        for project in projects:
            query = Query.from_string(project["env"], q)
            pjdb = project["env"].get_db_cnx()
            try:
                tickets = query.execute(req)
            except Exception, e:
                debug(traceback.format_exc())
            if len(tickets) == 0:
                 continue
            projs.append({'name': project["name"],
                          'href': project["href"],
                         'tickets': tickets})

        req.hdf["projects"] = projs
        req.hdf["chrome.nav.mainnav.tickets.active"] = 1
        req.hdf['title'] = _('View Tickets')
        req.hdf['show_myticket'] = show_myticket
        
        template_dir = os.path.dirname(__file__) + '/templates/'
        req.display(template_dir + "query.cs", 'text/html')
