# -*- coding: utf-8 -*-
from genshi.builder import tag

from trac.core import Component, implements
from trac.web.chrome import Chrome, add_stylesheet, add_script, \
                            add_script_data, ITemplateProvider
from trac.web.main import IRequestHandler, IRequestFilter
from trac.util.compat import partial
from trac.util.presentation import to_json

class TracAvatarModule(Component):
    implements(IRequestHandler, IRequestFilter, ITemplateProvider)

    # IRequestFilter methods
    def pre_process_request(self, req, handler):
        return handler
        
    def post_process_request(self, req, template, data, content_type):
        if data:
            req.callbacks['avatars'] = self._get_avatars
            if template == 'ticket.html' and 'ticket' in data:
                ticket = data['ticket']
                if data.has_key('owner_link'):
                    data['owner_link'] = tag(
                        self._avatar_image(req, ticket['owner']),
                        data['owner_link'])
                if data.has_key('reporter_link'):
                    data['reporter_link'] = tag(
                        self._avatar_image(req, ticket['reporter']),
                        data['reporter_link'])
            data['authorinfo'] = partial(self.authorinfo, req)
            data['format_author'] = partial(self.format_author, req)
        add_script_data(req, {'avatar_request_path': req.href.tracavatar(),
                              'form_token': req.form_token})
        add_stylesheet(req, 'tracavatar/css/avatar.css')
        add_script(req, 'tracavatar/js/avatar.js')
        return (template, data, content_type)

    def _get_avatars(self, req):
        db = self.env.get_read_db()
        cursor = db.cursor()
        cursor.execute("SELECT sid, value FROM session_attribute"
                       " WHERE authenticated=1 AND name='picture_href'")
        avatars = dict((sid, value) for sid, value in cursor)
        # default avatar
        avatars[None] = req.href.chrome('tracusermanager/img/no_picture.png')
        return avatars

    def _avatar_image(self, req, author):
        src = req.avatars.get(author) or req.avatars[None]
        return tag.img(src=src, class_='avatar')

    def authorinfo(self, req, author, email_map=None):
        return tag(self._avatar_image(req, author),
                   Chrome(self.env).authorinfo(req, author,
                                               email_map=email_map))

    def format_author(self, req, author):
        return tag(self._avatar_image(req, author),
                   Chrome(self.env).format_author(req, author))

    # IRequestHandler methods
    def match_request(self, req):
        if req.path_info in ('/login/tracavatar', '/tracavatar'):
            self.log.debug("%s matches %s" % (req.path_info, True))
            return True
        return False

    def process_request(self, req):
        sids = req.args.getlist('username')
        avatars = {}
        if sids:
            default = req.href.chrome('tracusermanager/img/no_picture.png')
            avatars = dict((sid, default) for sid in sids)
            query = "SELECT sid, value FROM session_attribute" + \
                    " WHERE sid IN(" + ','.join(['%s'] * len(sids)) + ")" + \
                    " AND authenticated=1 AND name='picture_href'"
            db = self.env.get_read_db()
            cursor = db.cursor()
            cursor.execute(query, sids)
            for sid, value in cursor:
                avatars[sid] = value

        response = to_json(avatars)
        if isinstance(response, unicode):
            response = response.encode('utf-8')
        req.send(response, 'application/json')

    # ITemplateProvider methods
    def get_templates_dirs(self):
        return []

    def get_htdocs_dirs(self):
        from pkg_resources import resource_filename
        return [('tracavatar', resource_filename(__name__, 'htdocs'))]