from django.shortcuts import get_object_or_404
from django.views.generic.dates import MonthArchiveView, YearArchiveView
from history.utils import history
from main.views import UserMixin
from transaction.models import Transaction


class ACFilterMixin:
    def get_queryset(self):
        queryset = super().get_queryset()
        if account := self.request.GET.get("account"):
            queryset = queryset.filter(statement__account=account)
        if category := self.request.GET.get("category"):
            queryset = queryset.filter(category=category)

        return queryset

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        if account := self.request.GET.get("account"):
            context_data["account"] = get_object_or_404(
                self.request.user.account_set, pk=account
            )
        if category := self.request.GET.get("category"):
            context_data["category"] = get_object_or_404(
                self.request.user.category_set, pk=category
            )

        return context_data


class TransactionMonthView(UserMixin, ACFilterMixin, MonthArchiveView):
    model = Transaction
    date_field = "date"
    context_object_name = "transactions"
    month_format = "%m"
    template_name = "history/transaction_month.html"


class TransactionYearView(UserMixin, ACFilterMixin, YearArchiveView):
    model = Transaction
    date_field = "date"
    context_object_name = "transactions"
    make_object_list = True
    template_name = "history/transaction_year.html"

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        h_data = context_data.get("transactions")
        if not (context_data.get("account") or context_data.get("category")):
            h_data = h_data.exclude(category__budget=False)
        context_data["history"] = history(h_data)

        return context_data
