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

import trac
from trac.web.chrome import add_stylesheet

from genshi.builder import tag
import genshi.core

class NestedTicketTable:
	def __init__(self, env, req, cols, nest_ticket_seq):
		env.log.debug('NestedTicketTable.__init__')
		self.env = env
		self.req = req
		self.cols = tuple(cols)
		self.nest_ticket_seq = nest_ticket_seq

		fields = trac.ticket.api.TicketSystem(env).get_ticket_fields()
		self.name2label = dict((f['name'], f['label']) for f in fields)
		add_stylesheet(self.req, 'common/css/report.css')

	def __iter__(self):
		self.env.log.debug('NestedTicketTable.__iter__')
		return self._generate()

	def __repr__(self):
		self.env.log.debug('NestedTicketTable.__repr__')
		return '<%s>' % self.__class__.__name__

	def __str__(self):
		self.env.log.debug('NestedTicketTable.__str__')
		return str(self.generate())

	def __unicode__(self):
		self.env.log.debug('NestedTicketTable.__unicode__')
		return unicode(self.generate())

	def __html__(self):
		raise NotImplementedError
		return genshi.core.Markup(self.generate())

	def append(self, node):
		self.env.log.debug('NestedTicketTable.append(%s)' % repr(node))
		raise NotImplementedError

	def generate(self):
		self.env.log.debug('NestedTicketTable.generate')
		return genshi.core.Stream(self._generate())

	def _generate(self):
		self.env.log.debug('NestedTicketTable._generate()')
		from itertools import chain
		
		it = tag.table(
			genshi.core.Stream(self._generate_hdr()),
			tag.tbody(
				genshi.core.Stream(self._generate_rows())
			),
			class_="listing tickets"
		)._generate()
		return it

	def _generate_hdr(self):
		hdr = tag.tr()
		cols = ('id', 'summary') + self.cols
		for col in cols:
			hdr.append(tag.th(
				self.name2label.get(col, col.capitalize()),
				class_=col
			))
		hdr = tag.thead(hdr)
		return hdr._generate()

	def _generate_rows(self):
		for rowno, (nesting, ticket) in enumerate(self.nest_ticket_seq):
			tkt = trac.ticket.model.Ticket(self.env, ticket)

			priority_value = trac.ticket.model.Priority(
				self.env, name=tkt['priority']
			).value

			summary = tkt['summary']

			id_class = tkt['status'] == 'closed' and 'closed' or None
			href = self.req.href.ticket(ticket)

			row = tag.tr(
				tag.td(
					tag.a(
						'#%s' % ticket,
						href=href,
						title="View ticket",
						class_=id_class
					),
					class_='id'
				),
				tag.td(
					tag.span(
						u'\u2514 ',
						tag.a(
							summary,
							href=href,
							title="View ticket",
							style='display: inline',
						),
					),
					class_='summary',
					style='padding-left: %dpx !important;' % (30 * nesting)

				),
				class_='%s prio%s' % (
					rowno % 2 and 'odd' or 'even',
					priority_value
				),
			)

			for col in self.cols:
				row.append(tag.td(tkt[col], class_=col))

			for ev in row._generate():
				yield ev

