from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic.base import ContextMixin, TemplateResponseMixin


__all__ = ("BaseView", "BaseAPIView")


class BaseView(TemplateResponseMixin, ContextMixin):
    related_count = 4
    related_carousel_count = 8
    title = ""

    @property
    def station(self):
        return self.request.station

    # def get_queryset(self):
    #    return super().get_queryset().station(self.station)

    def get_nav_menu(self):
        menu = []
        for item in self.station.navitem_set.all():
            try:
                if item.page:
                    view = item.page.get_related_view()
                    secondary = view and view.get_secondary_nav()
                else:
                    secondary = None
                menu.append((item, secondary))
            except:
                import traceback

                traceback.print_exc()
                raise
        return menu

    def get_secondary_nav(self):
        return None

    def get_related_queryset(self):
        """Return a queryset of related pages or None."""
        return None

    def get_related_url(self):
        """Return an url to the list of related pages."""
        return None

    def get_page(self):
        return None

    def get_context_data(self, **kwargs):
        kwargs.setdefault("station", self.station)
        kwargs.setdefault("page", self.get_page())

        if "model" not in kwargs:
            model = getattr(self, "model", None) or hasattr(self, "object") and type(self.object)
            kwargs["model"] = model

        page = kwargs.get("page")
        if page:
            kwargs.setdefault("title", page.display_title)
            kwargs.setdefault("cover", page.cover and page.cover.url)
        elif self.title:
            kwargs.setdefault("title", self.title)

        if "nav_menu" not in kwargs:
            kwargs["nav_menu"] = self.get_nav_menu()
        return super().get_context_data(**kwargs)

    def dispatch(self, *args, **kwargs):
        if not self.request.station:
            return HttpResponseRedirect(reverse("errors-no-station"))
        return super().dispatch(*args, **kwargs)


# FIXME: rename to sth like [Base]?StationAPIView/Mixin
class BaseAPIView:
    @property
    def station(self):
        return self.request.station

    def get_queryset(self):
        return super().get_queryset().station(self.station)
