import os

from trac import util
from trac.core import TracError
from trac.web.chrome import add_stylesheet
from trac.wiki import wiki_to_oneliner
from trac.util.translation import _

class BrowserModule(object):

    def process_request(self, req, chrome, projects):
        folders = []
        for project in projects:
            env = project["env"]
            if not req.authname:
                req.authname = "anonymous"
            try:
                repos = env.get_repository(req.authname)
            except TracError:
                continue
            try:
                change = repos.get_changeset(repos.get_youngest_rev())
                folders.append({'name': project["name"],
                            'href': project["href"]+"/browser",
                            'rev': repos.get_youngest_rev(),
                            'age': util.pretty_timedelta(change.date),
                            'author': change.author,
                            'message': wiki_to_oneliner(change.message, env, env.get_db_cnx(), shorten=True, absurls=True, req=req)})
            except Exception, e:
                pass
        
        data={}
        data["folders"] = folders
        data['title'] = _('Browse Source')
        data["chrome.nav.mainnav.browser.active"] = 1
        
        template_dir = os.path.dirname(__file__) + '/templates/'
        chrome.populate_data(req, data)
        output = chrome.render_template(req, template_dir + "browser.html", data)
        req.session.save()
        req.send(output, 'text/html')
