from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
from .models import Balance, Transaction
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 Media
from django.core.exceptions import PermissionDenied


# 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):
    if request.user.groups.filter(name='Cashier').exists():
        balRem = None
        if request.method == "POST":
            tokens = request.POST["tokens"]
            tokens = int(tokens) * -1
            user_given = request.POST["user_instance"]
            item = request.POST["item"]
            user_taken = request.user
            try:
                transAdd = Transaction.objects.create(client=user_given, cashier=user_taken, item=item)
                user_instance = Balance.objects.get(user=user_given)
                sum_balance = user_instance.balanceValue + tokens
                balRem = Balance(balanceValue=sum_balance, user_id=user_instance)
                balRem.save()
                print(balRem)
            except Balance.DoesNotExist:
                balRem = Balance(balanceValue=tokens, user_id=user_given)
                balRem.save()
            return render(request,"getBalance.html", {"userBalance":balRem})
        else:
            return render(request,"removeBalance.html")
    else:
        raise PermissionDenied("Unauthorized")

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):
    
    if request.user.groups.filter(name='Processor').exists():

        try:
            latestPicture = Media.objects.filter(tokenized=None)
            latestPicture, userId, date, time, is_video = latestPicture.values("image")[0]["image"], latestPicture.values("user_id")[0]["user_id"], latestPicture.values("date")[0]["date"], latestPicture.values("time")[0]["time"], latestPicture.values("is_video")[0]["is_video"]
            username = User.objects.get(pk=userId)

            if request.method == "POST":
                if request.POST['isValid'] == "Valid":
                    imageObj = Media.objects.get(image=latestPicture, user_id=userId)
                    
                    if imageObj.is_video:
                        token_count = 3
                    else:
                        token_count = 2

                    try:
                        user_instance = Balance.objects.get(user=userId)
                        sum_balance = token_count + user_instance.balanceValue
                        balAdd = Balance(balanceValue=sum_balance, user_id=user_instance)
                        balAdd.save()
                        print(balAdd)
                    except Balance.DoesNotExist:
                        balAdd = Balance(balanceValue=token_count, user_id=userId)
                        balAdd.save()
                    
                    imageObj.tokenized = True
                    imageObj.managed_by = request.user.username

                    imageObj.save()

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

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