# 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.

= TicketDep: Ticket dependency table =
Show a dependecy table for specified tickets.

== Usage ==
{{{
# Produce a dependency hierarchy of all tickets being blocked by <ticket_id>
[[TicketBlockees(<ticket_id>)]]

# Produce a dependency hierarchy of all tickets blocking <ticket_id>
[[TicketBlockers([<ticket_id>][,<depth>])]]
}}}
"""

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

from trac.core import *
from trac.wiki.macros import WikiMacroBase
from trac.wiki.api import parse_args

import trac.ticket.query

import genshi.core

from ticketdep.api import ticket_parents, ticket_children
from ticketdep.render import NestedTicketTable

class TicketBlockees(WikiMacroBase):
	"""
	TicketBlockees provides a macro for Trac to render a dependency table
	of tickets blocked by the given tickets(s) within a Trac wiki page.
	"""

	def expand_macro(self, formatter, name, content):
		args, kw = parse_args(content)
		ticket_id = int(args[0])

		cols = kw.get('cols', '').split('|')

		ticket_dep_seq = ticket_parents(self.env, ticket_id)

		dep_table = genshi.core.Stream(
			NestedTicketTable(self.env, formatter.req, cols, ticket_dep_seq)
		)
		return dep_table

class TicketBlockers(WikiMacroBase):
	"""
	TicketBlockers provides a macro for Trac to render a dependency table
	of tickets blocking the given tickets(s) within a Trac wiki page.
	"""

	def expand_macro(self, formatter, name, content):
		args, kw = parse_args(content)
		ticket_ids = map(int, args)
		max_depth = int(kw.get('maxdepth', '0'))
		query_string = kw.get('query', '')
		if query_string:
			query = trac.ticket.query.Query.from_string(self.env, query_string)
			tickets = query.execute(formatter.req)
			import itertools
			ticket_ids = itertools.chain(ticket_ids,(t['id'] for t in tickets))

		cols = kw.get('cols', '').split('|')

		if int(kw.get('combined', '0')):
			ticket_dep_seq = ticket_children(
				self.env, ticket_ids, max_depth
			).treeiter()
		else:
			ticket_dep_seq = ticket_children(self.env, ticket_ids, max_depth)

		dep_table = genshi.core.Stream(
			NestedTicketTable(self.env, formatter.req, cols, ticket_dep_seq)
		)
		return dep_table
