# -*- coding: utf-8 -*-

# This file is part of TracTicketDep.
#
# TracTicketDep is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# TracTicketDep is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Risto Kankkunen

"""
Copyright (c) 2008 Risto Kankkunen. All rights reserved.
"""

#__revision__  = '$LastChangedRevision$'
__id__        = '$Id$'
#__headurl__   = '$HeadURL$'
__version__   = '0.11'

import re

from pkg_resources import resource_filename

from trac.core import *
from trac.config import Option, BoolOption
from trac.mimeview.api import Context
from trac.web.api import IRequestFilter, IRequestHandler, ITemplateStreamFilter
from trac.web.chrome import ITemplateProvider, add_stylesheet, add_script
from trac.wiki.formatter import Formatter
from trac.util.html import html, Markup

from StringIO import StringIO

from genshi.filters.transform import Transformer
from genshi.input import XMLParser
from genshi.builder import tag

from mastertickets.model import TicketLinks

from ticketdep.macro import TicketBlockers, TicketBlockees

class TicketDepModule(Component):
	"""Embeds TicketBlocker and TicketBlockee tables into ticket pages"""

	cols = Option(
		'ticketdep', 'cols',
		default='milestone',
		doc='Columns to include in the Blockers/Blockee tables'
	)

	xpath = Option(
		'ticketdep', 'xpath',
		default='.//div[@id="ticket"]',
		doc=('XPath expression indicating the location where to '
		'inject Blockers/Blockee tables in the Trac ticket page')
	)

#	implements(ITemplateProvider)
	implements(ITemplateStreamFilter)
	# ITemplateStreamFilter methods
	def filter_stream(self, req, method, filename, stream, data):
		PATH_PREFIX = '/ticket/'
		if not req.path_info.startswith(PATH_PREFIX):
			return stream

		ticket_id = req.path_info[len(PATH_PREFIX):]

		context = Context.from_request(req, '')
		formatter = Formatter(self.env, context)

		parents = TicketLinks(self.env, ticket_id).blocking
		children = TicketLinks(self.env, ticket_id).blocked_by

		if len(children) > 0:
			dep_children_str = tag.div(
				tag.h2(u'子チケット'),
				TicketBlockers(self.env).expand_macro(
					formatter,
					'TicketBlockers',
					'%s, cols=%s' % (ticket_id, self.cols)
				),
				id='ticket_children_dep'
			)
			parser_children = XMLParser(StringIO(dep_children_str))
			stream |= Transformer(self.xpath).after(parser_children)

		if len(parents) > 0:
			dep_parent_str = tag.div(
				tag.h2(u'親チケット'),
				TicketBlockees(self.env).expand_macro(
					formatter,
					'TicketBlockees',
					'%s, cols=%s' % (ticket_id, self.cols)
				),
				id='ticket_parent_dep'
			)
			parser_parent = XMLParser(StringIO(dep_parent_str))
			stream |= Transformer(self.xpath).after(parser_parent)

		return stream

	# ITemplateProvider methods
	def get_templates_dirs(self):
		return [resource_filename(__name__, 'templates')]
	
	def get_htdocs_dirs(self):
		return []

	def __init__(self):
		self.log.info('version: %s - id: %s' % (__version__, str(__id__)))
