# -*- coding: utf-8 -*-
from trac.core import *
from trac.config import Option,  BoolOption, Configuration
from trac.web.chrome import add_script,add_stylesheet,ITemplateProvider,INavigationContributor
from trac.web.main import IRequestHandler, IRequestFilter
from trac.util.html import Markup
from trac.web.href import Href
import json

class CompleteUserWeb(Component):
    implements(IRequestHandler, IRequestFilter, ITemplateProvider, INavigationContributor)

    single_fields = Option('complete-user','single_fields','owner', u"""単一ユーザを補完するフィールド設定します。""");
    composite_fields = Option('complete-user','composite_fields','cc', u"""複数ユーザを補完するフィールド設定します。""");
    name_check = BoolOption('complete-user','name_check', 'True', u"""ユーザを検索する際にNameが設定されているユーザのみを検索するかどうかを設定します。""");
    popup_delay = Option('complete-user','popup_delay','1.5',
                        u"""補完ウィンドウのポップアップ表示までの遅延時間を設定します。
                        
                        単位は秒で小数点も利用することができます
                        """)

    # INavitationContributor methods
    def get_active_navigation_item(self, req):
        return "completeuser"

    def get_navigation_items(self, req):
        yield 'metanav', 'completeuser', ''

    # IRequestFilter methods
    def pre_process_request(self, req, handler):
        return handler
        
    def post_process_request(self, req, template, content_type):
        return (template, content_type)

    def post_process_request(self, req, template, content_type):
        if template == 'newticket.cs' or template == 'ticket.cs':
            single_fields = Configuration.getlist(self.config,"complete-user","single_fields","owner");
            composite_fields = Configuration.getlist(self.config,"complete-user","composite_fields","cc");
            popup_delay = Configuration.get(self.config,"complete-user","popup_delay","1.5")

            script = "<script type='text/javascript'>\n"
            script = script+"$(function(){\n"
            script = script+"  ultimania.trac.POPUP_DELAY = " + popup_delay + ";\n"
            script = script+"  ultimania.trac.setAutoComplete('reassign_owner','" + req.base_path + "/completeuser',false);\n"
            for field in single_fields:
               script = script+"  ultimania.trac.setAutoComplete('" + field + "','" + req.base_path + "/completeuser',false);\n"
            for field in composite_fields:
               script = script+"  ultimania.trac.setAutoComplete('" + field + "','" + req.base_path + "/completeuser',true);\n"
            script = script+"})\n"
            script = script+"</script>"
            script = req.hdf['project.footer'] + script

            add_stylesheet(req, 'completeuser/css/trac-completeuser.css')
            add_stylesheet(req, 'completeuser/js/yui/autocomplete/assets/skins/sam/autocomplete.css')
            add_script(req, 'completeuser/js/yui/utilities/utilities.js')
            add_script(req, 'completeuser/js/yui/autocomplete/autocomplete-min.js')
            add_script(req, 'completeuser/js/trac-completeuser.js')

            if req.perm.has_permission('TICKET_MODIFY') or req.perm.has_permission('TICKET_CREATE'):
                req.hdf['project.footer'] = Markup(script)

        return (template, content_type)

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

    def process_request(self, req):
        name_check = Configuration.getbool(self.config,"complete-user","name_check", "True");
        query = req.args.get('query')
        db = self.env.get_db_cnx()
        cursor = db.cursor();
        join = ""
        where  = ""
        
        if name_check:
            join = "JOIN"
        else:
            join = "LEFT OUTER JOIN"
        if query != None:
            where  = ("AND (s.sid LIKE '%%%s%%' or sa.value LIKE '%%%s%%')") % (query,query)
        
        sql = ("SELECT s.sid, sa.value FROM session s %s session_attribute sa ON s.sid = sa.sid AND sa.name = 'name' WHERE s.authenticated = 1 %s") % (join,where)
        
        cursor.execute(sql)
        userlist = []
        for sid, value in cursor:
            userlist.append({"Id":sid, "Name": value});
        response = json.write({"UserList":userlist});
	
        req.send_response(200)
        req.send_header('Content-Type', 'application/json; charset=utf-8')
        req.send_header('Content-Length', len(response.encode("utf-8")))
        req.end_headers()
        req.write(response)

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

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