import base64

from io import BytesIO
from PIL import Image

from django.contrib import messages
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse

from web.utils import send_email, is_member
from web.forms import SignupForm, EditProfileForm
from web.models.custom_user import CustomUser


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} \n\n https://members.christian-webring.org/accounts/user_management/ '
            )

            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')
