
from datetime import datetime, timedelta
from calendar import HTMLCalendar
from .models import Rdv

class Cal(HTMLCalendar):
	def __init__(self, year=None, month=None):
		self.year = year
		self.month = month
		super(Cal, self).__init__()

	# formats a day as a td
	# filter events by day
	def formatday(self, day, events):
		events_per_day = events.filter(rdvtime__day=day)
		d = ''
		for event in events_per_day:
			d += f'<li> {event.title} </li>'

		if day != 0:
			return f"<ul><span class='date'>{day}</span><li> {d} </li></ul>"
		return '<ul></ul>'

	# formats a week as a tr
	def formatweek(self, theweek, events):
		week = ''
		for d, weekday in theweek:
			week += self.formatday(d, events)
		return f'<ul> {week} </ul>'

	# formats a month as a table
	# filter events by year and month
	def formatmonth(self, withyear=True):
		events = Rdv.objects.filter(rdvtime__year=self.year, rdvtime__month=self.month)

		cal = f'\n'
		cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
		cal += f'{self.formatweekheader()}\n'
		for week in self.monthdays2calendar(self.year, self.month):
			cal += f'{self.formatweek(week, events)}\n'
		return cal