import json

from funcs import logThis

# Returns the account balance for a user
def checkBalance(user):
    user = user.lower()
    logThis("checking "+user+"'s account balance")
    with open("resources/games/games.json", "r") as f:
        data = json.load(f)
    
    if user in data["users"]:
        return data["users"][user]
    else: return 0

# Adds money to the account of a user
def addMoney(user,amount):
    user = user.lower()
    logThis("adding "+str(amount)+" to "+user+"'s account")
    with open("resources/games/games.json", "r") as f:
        data = json.load(f)
    
    if user in data["users"]:
        points = data["users"][user]
        data["users"][user] = points + amount
    else:
        data["users"][user] = amount
    
    with open("resources/games/games.json", "w") as f:
        json.dump(data,f,indent=4)

# Transfers money from one user to another
def giveMoney(user,targetUser,amount):
    with open("resources/games/games.json", "r") as f:
        data = json.load(f)
    
    if user in data["users"]:
        if data["users"][user] >= amount:
            addMoney(user,-1 * amount)
            addMoney(targetUser,amount)
            return "Transferred "+str(amount)+" GwendoBucks to "+targetUser
        else:
            logThis("They didn't have enough GwendoBucks (error code 1223b)")
            return "You don't have that many GwendoBucks (error code 1223b)"
    else:
        logThis("They didn't have enough GwendoBucks (error code 1223a)")
        return "You don't have that many GwendoBucks (error code 1223a)"
