import json

from funcs import logThis, getID, getName

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

    if user in data:
        return data[user]["money"]
    else: return 0

# Adds money to the account of a user
def addMoney(user,amount):
    logThis("adding "+str(amount)+" to "+user+"'s account")
    with open("resources/users.json", "r") as f:
        data = json.load(f)

    if user in data:
        points = data[user]["money"]
        data[user]["money"] = points + amount
    else:
        data[user]["money"] = amount

    with open("resources/users.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/users.json", "r") as f:
        data = json.load(f)

    targetUser = getID(targetUser)

    if amount > 0:
        if targetUser != None:
            if user in data:
                if data[user]["money"] >= amount:
                    addMoney(user,-1 * amount)
                    addMoney(targetUser,amount)
                    return "Transferred "+str(amount)+" GwendoBucks to "+getName(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)"
        else:
            logThis("They weren't in the system")
            return "The target doesn't exist"
    else:
        logThis("They tried to steal")
        return "Yeah, no. You can't do that"
