from collections.abc import Generator

from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.views import View
from icalendar import Calendar, Event


class CalendarResponse(HttpResponse):
    def __init__(self, calendar: Calendar, *args, **kwargs):
        kwargs["content"] = calendar.to_ical()
        kwargs["content_type"] = "text/plain" if settings.DEBUG else "text/calendar"
        super().__init__(*args, **kwargs)


class CalendarView(View):
    def get(self, request: HttpRequest, **kwargs) -> HttpResponse:
        cal = self.get_calendar(request, **kwargs)
        for event in self.get_events(request):
            cal.add_component(event)
        return CalendarResponse(cal)

    def get_calendar(self, request: HttpRequest, **kwargs) -> Calendar:
        cal = Calendar()
        # https://datatracker.ietf.org/doc/html/rfc5545#section-3.7.3
        cal.add("prodid", f"-//{request.site.name}/{self.__class__.__name__}//")
        cal.add("version", "2.0")
        cal.add("X-ORIGINAL-URL", request.build_absolute_uri())
        return cal

    def get_events(self, request: HttpRequest) -> Generator[Event]:
        yield Event()
