# encoding: utf-8

import re

from api import InformData

from genshi.builder import tag

from trac.core import *
from trac.ticket import model
from trac.web import IRequestHandler
from trac.web.api import IRequestFilter, ITemplateStreamFilter, IRequestHandler
from trac.web.chrome import INavigationContributor
from trac.web.chrome import ITemplateProvider, add_stylesheet

class InformList(Component):
    implements(INavigationContributor, IRequestHandler, ITemplateProvider)

    # INavigationContributor methods
    def get_active_navigation_item(self, req):
        return 'inform'

    def get_navigation_items(self, req):
        yield ('mainnav', 'inform',
               tag.a(u'周知事項', href=req.href.inform()))

    # IRequestHandler methods
    def match_request(self, req):
        return req.path_info == '/inform'

    # IRequestHandler methods
    def process_request(self, req):
        data = {}
        
        # リクエスト情報取得
        data["selected_milestone"] = req.args.get('milestone')
        if data["selected_milestone"] is None:
            data["selected_milestone"] = ""
        data["selected_component"] = req.args.get('component')
        if data["selected_component"] is None:
            data["selected_component"] = ""
        data["selected_priority"] = req.args.get('priority')
        if data["selected_priority"] is None:
            data["selected_priority"] = ""
        data["selected_type"] = req.args.get('type')
        if data["selected_type"] is None:
            data["selected_type"] = ""
        
        # 検索条件作成
        where = ""
        if data["selected_milestone"] != "":
            where += " AND t.milestone='%s'" % (data["selected_milestone"])
        if data["selected_component"] != "":
            where += " AND t.component='%s'" % (data["selected_component"])
        if data["selected_priority"] != "":
            where += " AND t.priority='%s'" % (data["selected_priority"])
        if data["selected_type"] != "":
            where += " AND t.type='%s'" % (data["selected_type"])

        db = self.env.get_db_cnx()
        cursor = db.cursor();
        sql = "SELECT i.ticket,t.summary, i.question FROM inform i, ticket t WHERE i.ticket=t.id" + where
        cursor.execute(sql)
        ticketlist = []
        userlist = []
        usernamelist = []
        for ticket, summary, question in cursor:
            informlist = InformData(ticket, self.env).getInformDb()
            ticketlist.append({"id":ticket, "summary": summary, "question":question, "userlist":informlist})
            for informlist_item in informlist:
                id = informlist_item["id"]
                name = informlist_item["name"]

                if not id in userlist:
                    userlist.append(id)
                    usernamelist.append(name)
        
        data["ticketlist"] = ticketlist
        data["usernamelist"] = usernamelist

        tabledata = []
        for t in ticketlist:
            tabledata_item = []
            for u in userlist:
                f = True
                for tu in t["userlist"]:
                    if tu["id"] == u and f:
                        f = False
                        tabledata_item.append(tu["result"])
                if f:
                    tabledata_item.append(None)

            tabledata.append(tabledata_item)
            t["tabledata"] = tabledata_item

        data["tabledata"] = tabledata

        # 検索用データ取得
        data["milestones"] = [val.name for val in model.Milestone.select(self.env, db=db)]
        if len(data["milestones"]) > 0:
            data["milestones"].insert(0, "")
        else:
            data["milestones"] = None
            
        data["components"] = [val.name for val in model.Component.select(self.env, db=db)]
        if len(data["components"]) > 0:
            data["components"].insert(0, "")
        else:
            data["components"] = None
            
        data["priority"] = [val.name for val in model.Priority.select(self.env, db=db)]
        if len(data["priority"]) > 0:
            data["priority"].insert(0, "")
        else:
            data["priority"] = None
            
        data["typelist"] = [val.name for val in model.Type.select(self.env, db=db)]
        if len(data["typelist"]) > 0:
            data["typelist"].insert(0, "")
        else:
            data["typelist"] = None
            
        
        
        add_stylesheet(req, 'inform/css/inform.css')

        return 'list.html', data, None

    # ITemplateProvider method
    def get_htdocs_dirs(self):
        from pkg_resources import resource_filename
        return [('inform', resource_filename(__name__, 'htdocs'))]

    # ITemplateProvider methods
    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__, 'templates')]
    
    def changeTategaki(self, str):
        r = ''
        for c in str:
            r += c
            r += '<br>'
        return r
