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'
        query_param = 'all'
        show_myticket = 0
        if not req.authname:
            req.authname = "anonymous"
        else:
            show_myticket = 1
            query_param = req.args.get('query')
            if query_param == "mine":
                q = 'status=new|assigned|accepted|reopened&owner=$USER'
            elif query_param == "reported_by_me":
                q = 'status=new|assigned|accepted|reopened&reporter=$USER'
            else:
                query_param = "all"

        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
        data['query'] = query_param

        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')
