from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
from .models import Balance
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from django.contrib import messages
from upload.models import Image

# need to make oauth facebook login
class SignUpView(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

def addToBalance(request):
    balAdd = None
    if request.method == "POST":
        tokens = request.POST["tokens"]
        tokens = int(tokens)
        user_given = request.POST["user_instance"]
        try:
            user_instance = Balance.objects.get(user=user_given)
            sum_balance = tokens + user_instance.balanceValue
            balAdd = Balance(balanceValue=sum_balance, user_id=user_instance)
    # balAdd = balAdd() + testVar
            balAdd.save()
            print(balAdd)
            return render(request, "addBalance.html", {"message": f"Added balance to user {user_given}"})
        except Balance.DoesNotExist:
            balAdd = Balance(balanceValue=tokens, user_id=user_given)
            balAdd.save()
            return render(request, "addBalance.html", {"message": f"Created and added tokens to {user_given}'s token account"})

            
    else:
        return render(request,"addBalance.html")

def removeBalance(request):
    balRem = None
    if request.method == "POST":
        tokens = request.POST["tokens"]
        tokens = int(tokens)
        user_given = request.POST["user_instance"]
        try:
            user_instance = Balance.objects.get(user=user_given)
            sum_balance = user_instance.balanceValue - tokens
            balAdd = Balance(balanceValue=sum_balance, user_id=user_instance)
            balAdd.save()
            print(balAdd)
        except Balance.DoesNotExist:
            messages.error(request, f"User{user_given} doesn't have balance")
        return render(request,"getBalance.html", {"userBalance":balAdd})
    else:
        return render(request,"removeBalance.html")

def getBalance(request):
    balObject = Balance.objects.filter(user=request.user.id)
    print(dir(balObject))
    userBalance = balObject.values("balanceValue")
    # userBalance = userBalance[0]["balanceValue"]


    return render(request,"getBalance.html", {"userBalance":userBalance} )
    
def adminView(request):
    try:
        latestPicture = Image.objects.filter(tokenized=None)
        latestPicture, userId, date, time = latestPicture.values("image")[0]["image"], latestPicture.values("user_id")[0]["user_id"], latestPicture.values("date")[0]["date"], latestPicture.values("time")[0]["time"]
        username = User.objects.get(pk=userId)
        if request.method == "POST":
            if request.POST['isValid'] == "Valid":
                try:
                    user_instance = Balance.objects.get(user=userId)
                    sum_balance = 5 + user_instance.balanceValue
                    balAdd = Balance(balanceValue=sum_balance, user_id=user_instance)
                    balAdd.save()
                    print(balAdd)
                except Balance.DoesNotExist:
                    balAdd = Balance(balanceValue=5, user_id=userId)
                    balAdd.save()
                
                imageObj = Image.objects.get(image=latestPicture, user_id=userId)
                imageObj.tokenized = True
                imageObj.save()

                return redirect("/admin/")
            elif request.POST['isValid'] == "Invalid":
                imageObj = Image.objects.get(image=latestPicture, user_id=userId)
                imageObj.tokenized=True
                imageObj.reason="Invalid"
                imageObj.save()
                return render(request, "adminView.html", {"time":time, "date":date,"image":latestPicture, "userId":userId, "username":username})
            

            else:
                return render(request, "adminView")
        return render(request, "adminView.html", {"time":time, "date":date,"image":latestPicture, "userId":userId, "username":username})   
    except IndexError:
        return render(request, "adminView.html")   
