# -*- coding: utf-8 -*-
# This software include silk icon set.
#   http://www.famfamfam.com/lab/icons/silk/
#
from trac.core import *
from trac.config import Option, BoolOption, Configuration
from trac.web.chrome import add_script,add_stylesheet,ITemplateProvider
from trac.web.api import ITemplateStreamFilter
from trac.web.main import IRequestFilter
from trac.util.html import Markup

from genshi.filters.transform import Transformer
from genshi.template import MarkupTemplate

import os
import re

# This module provide decoration for ticket fields and report.
# To configurate this plugin, edit trac.ini.
# 
# = trac.ini =
# ..
# [decorator]
# # wheather use iconized report
# iconized_report=True
# # fields list to add calendar feature
# calendar_fields=due_assign, due_close
#
# # configure icon set for iconized report.
# type.task=decorator/icons/page_edit.png
# type.defect=decorator/icons/bug.png
# type.enhancement=decorator/icons/page_add.png
#
# priority.blocker = decorator/icons/blocker.png
# priority.critical = decorator/icons/critical.png
# priority.major = decorator/icons/major.png
# priority.minor = decorator/icons/minor.png
# priority.trivial = decorator/icons/trivial.png
#
# status.assigned=decorator/icons/user_gray.png
# status.accepted=decorator/icons/user_gray.png
# status.new=decorator/icons/new.png
# status.closed=decorator/icons/tick.png
# status.reopened=decorator/icons/door_out.png
# status.verify=decorator/icons/magnifier.png
#
#
# # configure icon set for iconized report in Japanese.
# type.タスク=decorator/icons/page_edit.png
# type.バグ=decorator/icons/bug.png
# type.不具合=decorator/icons/bug.png
# type.機能追加=decorator/icons/page_add.png
# type.仕様変更=decorator/icons/page_refresh.png
# type.課題=decorator/icons/page_white_error.png
# type.質問=decorator/icons/help.png

# priority.重大 = decorator/icons/blocker.png
# priority.緊急 = decorator/icons/critical.png
# priority.高 = decorator/icons/major.png
# priority.中 = decorator/icons/minor.png
# priority.低 = decorator/icons/trivial.png
#
# status.assigned=decorator/icons/user_gray.png
# status.accepted=decorator/icons/user_gray.png
# status.new=decorator/icons/new.png
# status.closed=decorator/icons/tick.png
# status.reopened=decorator/icons/door_out.png
# status.verify=decorator/icons/magnifier.png

class DecoratorModule(Component):
    implements(ITemplateStreamFilter, ITemplateProvider)

    iconized_report = BoolOption('decorator', 'iconized_report','false',
                             u"""レポートのアイコン化を行うかどうかを設定します。
                             
                             利用するには別途trac.iniでの設定が必要です。""")
    calendar_fields = Option('decorator', 'calendar_fields','',u"""カレンダーピックアップを利用するフィールドを設定します。""")
    ext_decoration  = BoolOption('decorator', 'ext_decoration','true',u"""セレクトボックスのルックアップを利用するかどうかを設定します。""")

    def filter_stream(self, req, method, filename, stream, data):
        if re.match(r'^/(ticket|newticket|report)', req.path_info):
            calendar_fields = Configuration.getlist(self.config,"decorator","calendar_fields","due_assign,due_close");
            iconized_report = Configuration.getbool(self.config,"decorator","iconized_report", "True");
            ext_decoration = Configuration.getbool(self.config,"decorator","ext_decoration", "True");
            add_stylesheet(req, 'decorator/js/yui/calendar/assets/calendar.css')
            if ext_decoration:
                add_stylesheet(req, 'decorator/js/ext/resources/css/form.css')
                add_stylesheet(req, 'decorator/js/ext/resources/css/combo.css')
            add_script(req, 'decorator/js/yui/yahoo/yahoo-min.js')
            add_script(req, 'decorator/js/yui/yahoo/yahoo-min.js')
            add_script(req, 'decorator/js/yui/event/event-min.js')
            add_script(req, 'decorator/js/yui/dom/dom-min.js')
            add_script(req, 'decorator/js/yui/calendar/calendar-min.js')
            if ext_decoration:
                add_script(req, 'decorator/js/ext/adapter/ext/ext-base.js')
                add_script(req, 'decorator/js/ext/adapter/jquery/jquery-plugins.js')
                add_script(req, 'decorator/js/ext/ext-all.js')
            add_script(req, 'decorator/js/trac-decorator.js')

            calendar_fields = Configuration.getlist(self.config,"decorator","calendar_fields","due_assign,due_close");
            iconized_report = Configuration.getbool(self.config,"decorator","iconized_report", "True");
            ext_decoration = Configuration.getbool(self.config,"decorator","ext_decoration", "True");
            script = "<script type='text/javascript'>\n"
            script = script+"window.onload = function(){\n"
            script = script+"  ultimania.trac.base = '" + req.href.chrome('decorator') + "';\n"

            for field in calendar_fields:
                script = script+"  ultimania.trac.addCalendar('field-" + field + "');\n"

            if iconized_report:
                config = self.config['decorator']
                for (value, icon) in config.options():
                    try:
                        idx = value.index('.')
                        field = value[0:idx]
                        name = value[idx+1:]
                        script = script+self.generate_decorator(field ,name ,icon ,req)
                    except ValueError:
                        None
                script = script+"  ultimania.trac.decorate();\n"

            script = script+"}\n"
            if ext_decoration:
                script = script+"  Ext.BLANK_IMAGE_URL = '"+req.href.chrome('decorator/js/ext/resources/images/default/s.gif')+"';\n"
                script = script+"  ultimania.trac.initExt();\n"
            script = script+"</script>"
            return stream | Transformer('//div[@id="footer"]').before(MarkupTemplate(script).generate())
        else:
            return stream

    def generate_decorator(self,fieldname, name, icon, req):
        return "  ultimania.trac.registDecorator('"+fieldname+"','"+name+"','"+req.href.chrome(icon)+"');\n"

    def get_templates_dirs(self):
        from pkg_resources import resource_filename
	return []
#        return [resource_filename(__name__, 'templates')]

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


        