from collections import deque

from django.shortcuts import render

from posts.models import Post, FetMeeting, Event


def index(request):
    posts = deque(Post.articles.date_sorted_list())
    posts_for_tags = deque(Post.objects.get_last_months_posts())

    def get_tags(lst):
        for p in lst:
            for t in list(p.tags.names()):
                yield "#" + t

    t = set(t for t in get_tags(posts_for_tags))

    # set the pinned post
    pinned_post = Post.articles.pinned()
    if not pinned_post:
        # if a pinned post does not exist, take the last published one.
        if len(posts) >= 1:
            pinned_post = posts.popleft()
    else:
        # remove the pinned post
        posts.remove(pinned_post)

    featured_event = Event.only_events.future_events().first()
    # if there is no futurity event
    if not featured_event:
        featured_event = Event.only_events.past_events().first()

    featured_meeting = deque([])
    featured_meeting.append(FetMeeting.objects.future_events().first())
    featured_meeting.append(FetMeeting.objects.past_events().first())

    context = {
        "posts": deque(list(posts)[:5]),
        "events": Event.all_events.future_events()[:5],
        "featured_post": pinned_post,
        "featured_event": featured_event,
        "featured_meeting": featured_meeting,
        "tags_list": "&nbsp;".join(t),
    }

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