from django.shortcuts import render
import os.path
from users.models import Balance
from django.conf import settings
from users.models import User
import operator
from upload.models import Media
import requests

def homePage(request):
    iter_var = 0
    all_balance = []
    Cashier = False
    Processor = False

    
    balObject = Balance.objects.filter(user=request.user.id)
    userBalance = balObject.values("balanceValue")
    try:
        userBalance = userBalance[0]['balanceValue'] 
    except IndexError:
        userBalance = None
    if request.user.groups.filter(name='Cashier').exists():
        Cashier = True
    elif request.user.groups.filter(name='Processor').exists():
        Processor = True
    else:
        pass
    if request.user.is_authenticated:
        userQR = f"Name = {request.user.username}, Date Joined = {request.user.date_joined.date()}, ID = {request.user.id}, isCashier={Cashier}, isProcessor={Processor}, Balance = {userBalance}"
    else:
        userQR=None
    a = Balance.objects.all()

    for user in a:
        all_balance.append(user.balanceValue)
    print(f"{all_balance}")
    limited_coins = settings.ALL_COINS - sum(all_balance)

    github = requests.get("https://api.github.com/user/36108495").json()

    context = {
        "isCashier": Cashier,
        "isProcessor": Processor,
        "userQR":userQR,
        "fullbalance": limited_coins,
        "currencyTotal": sum(all_balance),
        "userBalance": userBalance,
        "github": f"https://github.com/{github['login']}",
    }

            
    return render(request, "home.html", context)
    

def leaderboard(request):
    users = User.objects.all()
    leaderboard = {}
    for i in users:
        try:
            username = i.username
            balance = i.balance.balanceValue
            # add media counter and other stuff 
            if f"{username}" in leaderboard.keys():
                leaderboard[username] = balance + leaderboard[username]
            else:
                leaderboard[username] = balance    
        except Exception as e:
            pass
        
    leaderboard = dict(sorted(leaderboard.items(), key=operator.itemgetter(0)))
    leaderboard = dict(reversed(list(leaderboard.items())))

    while len(leaderboard) > 5:
        leaderboard.pop()
    

    media = Media.objects.all() 
    user_media = {}
    for i in media:
        username = i.user.username
        if f"{username}" in user_media.keys():
            user_media[username] += 1
        else:
            user_media[username] = 1
    
    user_media = dict(sorted(user_media.items(), key=operator.itemgetter(0)))
    user_media = dict(reversed(list(user_media.items())))
    print(user_media)
    users = {}
    for i in user_media.keys():
        iter_user = User.objects.get(username=i)
        iter_user_media = Media.objects.filter(user=iter_user)
        if iter_user_media.filter(is_video=True):
            user_data = {i:{"Videos":len(iter_user_media.filter(is_video=True)),
                        "Images":len(iter_user_media.filter(is_video=False))}}
        else:
            user_data = {i:{"Images":len(iter_user_media.filter(is_video=False))}}
    print(user_data)
    
    while len(user_media) > 5:
        user_media.pop()

    # for i in media:
    #     username = i.user.username
    #     image = i.image

    #     if f"{username}" in media_count.values():
    #         media_count[username] = image + media_count[username].value
    #     else:
    #         media_count[username] = image   
    
    # print(media_count)

    context = {
        "leaderboard":leaderboard,
        "user_media":user_media
    }

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