from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.paginator import Paginator
from django.shortcuts import redirect, render, get_object_or_404, reverse
from markdownx.utils import markdownify

from web.utils import is_member
from web.forms import ThreadPostForm
from web.models.custom_user import CustomUser
from web.models.forum_subcategory import ForumSubcategory
from web.models.forum_post import ForumPost


@login_required
@user_passes_test(is_member, login_url='/accounts/denied/')
def forum_threads(request):
    parsed_forum_threads = {}
    forum_subcategories = ForumSubcategory.objects.filter(active=True).order_by('created_at').order_by('-sticky').all()

    for forum_subcategory in forum_subcategories:
        if forum_subcategory.forum_category.title not in parsed_forum_threads:
            parsed_forum_threads[forum_subcategory.forum_category.title] = []

        data = {
            'id': forum_subcategory.id,
            'title': forum_subcategory.title,
            'description': forum_subcategory.description,
            'post_count': len(forum_subcategory.posts.all()),
            'most_recent_poster': forum_subcategory.posts.last().created_by if forum_subcategory.posts.last() else 'admin',
            'most_recent_poster_id': forum_subcategory.posts.last().created_by.id if forum_subcategory.posts.last() else '#',
            'most_recent_post_date': forum_subcategory.posts.last().created_at if forum_subcategory.posts.last() else forum_subcategory.created_at,
        }

        parsed_forum_threads[forum_subcategory.forum_category.title].append(data)

    context = {
        'threads': parsed_forum_threads
    }
    return render(request, 'forum_threads.html', context)


@login_required
@user_passes_test(is_member, login_url='/accounts/denied/')
def thread(request, thread_id, page=None):
    thread = get_object_or_404(ForumSubcategory, pk=thread_id)

    if request.method == 'POST':
        anonymous = False
        form = ThreadPostForm(request.POST)
        if form.is_valid():
            if 'anonymous' in form.data:
                if form.data['anonymous'] == 'on':
                    anonymous = True
            post = ForumPost(
                content=markdownify(form.data['content']),
                forum_subcategory=thread,
                created_by=CustomUser.objects.filter(username='Anonymous').first() if anonymous else request.user,
                edited=False,
                sticky=False,
            )
            post.save()
            return redirect(reverse('thread', kwargs={"thread_id": thread_id}, query={"page": "last"}))

    form = ThreadPostForm()
    posts = ForumPost.objects.filter(forum_subcategory=thread).all()
    paginator = Paginator(posts, 10)
    page_number = request.GET.get('page')
    paginated_posts = paginator.get_page(page_number if page_number != 'last' else paginator.num_pages)

    context = {
        'can_be_anon': thread.can_by_anon,
        'thread_name': thread.title,
        'thread_category': thread.forum_category.title,
        'posts': paginated_posts,
        'form': form
    }
    return render(request, 'thread.html', context)
