from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import get_object_or_404, render

from taggit.models import Tag
from wagtail.models import Site

from .models import ArticlePage, CATEGORY_HOT_SIZE, PAGE_SIZE
from .pagination import build_pagination_context, get_page_size


def hashtag_search(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    articles = (
        ArticlePage.objects.live()
        .filter(tags__slug=slug)
        .order_by("-date", "-id")
    )

    paginator = Paginator(articles, get_page_size(request, PAGE_SIZE))
    page_number = request.GET.get("page")

    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)

    site = Site.find_for_request(request)
    site_root = site.root_page if site else None

    context = {
        "tag": tag,
        "category_sections": [
            {
                "title": f"#{tag.name}",
                "items": page_obj,
                "url": request.path,
                "pagination": build_pagination_context(request, page_obj, paginator),
            }
        ],        
        "category_trending": (
            ArticlePage.objects.live()
            .filter(tags__slug=slug, trending=True)
            .order_by("-date", "-id")[:CATEGORY_HOT_SIZE]
        ),
        "site_root": site_root,
        "page": site_root.specific if site_root else None,
    }

    return render(request, "home/hashtag_page.html", context)
