import base64
from io import BytesIO
from PIL import Image

from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib import messages
from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from markdownx.utils import markdownify

from web.forms import SignupForm, ThreadPostForm, EditProfileForm
from web.models.forum_subcategory import ForumSubcategory
from web.models.forum_post import ForumPost
from web.models.custom_user import CustomUser

def test_email(request):
    send_mail(
        subject='test email',
        message='test email',
        from_email='noreply@christian-webring.org',
        recipient_list=['me@domdit.com'],
        fail_silently=False,
    )
    return redirect('index')


def send_email(subject, message, recipients=None):
    send_mail(
        subject=subject,
        message=message,
        from_email='noreply@christian-webring.org',
        recipient_list=recipients or ['domdit@gmail.com', 'me@domdit.com'],
        fail_silently=False,
    )


def is_member(user):
    if user.is_authenticated:
        return user.groups.filter(name='Member').exists()
    return False


# ACCOUNT MANAGEMENT ######################################
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, "You have successfully applied for membership, we will review your submission and send you an email once we have added you as a member! In the meantime, please start setting up the webring widget on your website!")

            send_email(
                subject='New User Sign Up Alert',
                message=f'A new user has signed up for the webring, please review the user in the admin portal! \n\n ID: {user.id}, EMAIL: {user.email}, USERNAME: {user.username}'
            )

            send_email(
                subject='Christian Web Ring - Thanks for Joining',
                message=f'Hello {user.username}! \n Thank you for signing up for the Christian Web Ring. We will reach out to you soon once we have approved your account. In the meantime, please add the widget to your page. Instructions can be found here: https://christian-webring.nekoweb.org/widget.html \n Remember, we cannot add you to the webring until you have completed this step! \n\n Thanks, \n Christian Webring Admins',
                recipients=[user.email]
            )

            return redirect(reverse('login'))
    else:
        form = SignupForm()

    context = {
        'form': form
    }
    return render(request, 'signup.html', context)


def denied(request):
    messages.warning(request, "You are not a member yet and cannot access the member site. Please wait for an admin to add you. If you have waited a long time, please send an email to domdit@gmail.com")
    return redirect(reverse('login'))


@login_required
@user_passes_test(is_member, login_url='/accounts/denied/')
def custom_logout(request):
    logout(request)
    return redirect(reverse('login'))


@login_required
@user_passes_test(is_member, login_url='/accounts/denied/')
def profile(request):
    if request.method == 'POST':
        form = EditProfileForm(request.POST)
        if form.is_valid():
            if request.FILES:
                avatar_size = 200, 200
                image = Image.open(request.FILES['avatar'])
                image.thumbnail(avatar_size, Image.Resampling.LANCZOS)

                buffered = BytesIO()
                image.save(buffered, format="png")
                img_str = base64.b64encode(buffered.getvalue())
                img_base64 = bytes("data:image/png;base64,", encoding='utf-8') + img_str
                request.user.avatar = img_base64.decode('utf-8')

            request.user.description = request.POST['description']
            request.user.url = request.POST['url']
            request.user.save()

    form = EditProfileForm()

    context = {
        'user': request.user,
        'form': form,
    }
    return render(request, 'profile.html', context)


@login_required
@user_passes_test(is_member, login_url='/accounts/denied/')
def user_profile(request, user_id):
    context = {
        'user': get_object_or_404(CustomUser, pk=user_id),
    }
    return render(request, 'user.html', context)


def code_of_ethics(request):
    return render(request, 'code_of_ethics.html')


# FORUM ###################################################
@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.first().created_by if forum_subcategory.posts.first() else 'admin',
            'most_recent_post_date': forum_subcategory.posts.first().created_at if forum_subcategory.posts.first() 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):
    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()

    form = ThreadPostForm()
    posts = ForumPost.objects.filter(forum_subcategory=thread).all()

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


# API ##############################################
def users(request):
    parsed_users = {'users': []}
    admin_only = request.GET.get('admin', False)
    users = CustomUser.objects.filter(is_active=True).filter(groups__name='Member')
    if admin_only == 'true':
        users = users.filter(is_superuser=True)

    users = users.all().values('username', 'description', 'url')
    for user in users:
        parsed_users['users'].append(user)
    return JsonResponse(parsed_users)
