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, chrome, projects):

        q = 'status=new|assigned|accepted|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|accepted|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})
        data = {}
        data["projects"] = projs
        data["chrome.nav.mainnav.tickets.active"] = 1
        data['title'] = _('View Tickets')
        data['show_myticket'] = show_myticket

        template_dir = os.path.dirname(__file__) + '/templates/'
        chrome.populate_data(req, data)
        output = chrome.render_template(req, template_dir + "query.html", data)
        req.session.save()
        req.send(output, 'text/html')
