from django.shortcuts import render, redirect
from .models import Club, BookRecommendation, ClubMembership
from django.db import IntegrityError
import random

def index(request):
    if request.method == 'POST':
        club_id = request.POST.get('club')
        book_title = request.POST.get('book_title')
        author = request.POST.get('author')
        reason = request.POST.get('reason')
        # Simple CAPTCHA
        num1 = int(request.POST.get('num1'))
        num2 = int(request.POST.get('num2'))
        captcha = int(request.POST.get('captcha'))

        if captcha == num1 + num2:
            club = Club.objects.get(id=club_id)
            BookRecommendation.objects.create(
                club=club,
                book_title=book_title,
                author=author,
                reason=reason,
            )
            return redirect('/?submitted=true')
        else:
            return redirect('/?captcha_error=true')


    clubs = Club.objects.all()
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    submitted = request.GET.get('submitted')
    captcha_error = request.GET.get('captcha_error')
    return render(request, 'core/index.html', {
        'clubs': clubs, 
        'num1': num1, 
        'num2': num2,
        'submitted': submitted,
        'captcha_error': captcha_error,
    })

from django.contrib.auth import login, logout, get_user
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from .forms import SignUpForm

def signup_view(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('/')
    else:
        form = SignUpForm()
    return render(request, 'core/signup.html', {'form': form})

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('/')
    else:
        form = AuthenticationForm()
    return render(request, 'core/login.html', {'form': form})

def logout_view(request):
    if request.method == 'POST':
        logout(request)
        return redirect('/')

@login_required
def club_list(request):
    if request.method == 'POST':
        club_id = request.POST.get('club_id')
        club = Club.objects.get(id=club_id)
        user = get_user(request)
        try:
            ClubMembership.objects.create(user=user, club=club)
            message = f"You have successfully joined {club.name}."
        except IntegrityError:
            message = f"You are already a member of {club.name}."
        clubs = Club.objects.all()
        return render(request, 'core/club_list.html', {'clubs': clubs, 'message': message})

    clubs = Club.objects.all()
    return render(request, 'core/club_list.html', {'clubs': clubs})