from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.models import Group
from django.shortcuts import render

from web.utils import send_email, is_superuser
from web.models.custom_user import CustomUser


@login_required
@user_passes_test(is_superuser, login_url='/accounts/denied/')
def manage_users(request):
    context = {}

    if request.method == 'POST':
        if 'make_member' in request.POST:
            user_id = request.POST.get('make_member')
            user = CustomUser.objects.filter(id=user_id).first()
            member_group = Group.objects.get(name='Member')
            user.groups.add(member_group)
            send_email(
                subject='Christian Webring - You have been added as a member!',
                message=f'Hello {user.username},\n\nYou have been added as a member to the christian webring, please login here: https://members.christian-webring.org \n\n Thanks, \n the Christian Webring Team',
                recipients=[user.email]
            )
            messages.success(request, f"You added {user.username} as a member!")

    non_members = []
    members = []
    users = CustomUser.objects.all()
    for user in users:
        if user.groups.filter(name='Member').exists():
            user.is_member = True
            members.append(user)
        else:
            user.is_member = False
            non_members.append(user)

    non_members.extend(members)

    context['parsed_users'] = non_members

    return render(request, 'user_management.html', context)

