# -*- 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,INavigationContributor
from trac.web.main import IRequestFilter
from trac.util.html import Markup
from trac.web.href import Href

import os, 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/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(IRequestFilter, ITemplateProvider, INavigationContributor)

    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 get_active_navigation_item(self, req):
        return "decorator"

    def get_navigation_items(self, req):
        yield 'metanav', 'decorator', ''
        
                   
    # IRequestFilter methods
    def pre_process_request(self, req, handler):
        return handler
        

    def post_process_request(self, req, template, content_type):
        if template == 'newticket.cs' or template == 'ticket.cs' or template == 'report.cs':
            calendar_fields = Configuration.getlist(self.config,"decorator","calendar_fields","");
            iconized_report = Configuration.getbool(self.config,"decorator","iconized_report", "True");
            ticketdelete_web = Configuration.get(self.config,"components","ticketdelete.web_ui.ticketdeleteplugin", "disabled");
            ticketdelete_all = Configuration.get(self.config,"components","ticketdelete.*", "disabled");

            add_script(req, 'decorator/js/ext/adapter/jquery/jquery.js')

            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')



            script = "<script type='text/javascript'>\n"
            script = script+"window.onload = function(){\n"
            script = script+"  ultimania.trac.base = '" + req.href.chrome('decorator') + "';\n"

            if (req.perm.has_permission('TICKET_MODIFY') and template == 'ticket.cs') or (req.perm.has_permission('TICKET_CREATE') and template == 'newticket.cs'):
                if len(calendar_fields) > 0:
                    for field in calendar_fields:
                        script = script+"  ultimania.trac.addCalendar('" + field + "');"

            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>"
            script = req.hdf['project.footer'] + script
            req.hdf['project.footer'] = Markup(script)

        return (template, content_type)

    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 [resource_filename(__name__, 'templates')]

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

        