from funcs import logThis

class Money():

    def __init__(self, bot):
        self.bot = bot
        self.database = bot.database

    # Returns the account balance for a user
    def checkBalance(self, user):
        logThis("checking "+user+"'s account balance")

        userData = self.database["users"].find_one({"_id":user})

        if userData != None:
            return userData["money"]
        else: return 0

    # Adds money to the account of a user
    def addMoney(self,user,amount):
        logThis("adding "+str(amount)+" to "+user+"'s account")

        userData = self.database["users"].find_one({"_id":user})

        if userData != None:
            self.database["users"].update_one({"_id":user},{"$inc":{"money":amount}})
        else:
            self.database["users"].insert_one({"_id":user,"user name":self.bot.funcs.getName(user),"money":amount})

    # Transfers money from one user to another
    def giveMoney(self,user,targetUser,amount):
        userData = self.database["users"].find_one({"_id":user})
        targetUser = self.bot.funcs.getID(targetUser)

        if amount > 0:
            if targetUser != None:
                if userData != None:
                    if userData["money"] >= amount:
                        self.addMoney(user,-1 * amount)
                        self.addMoney(targetUser,amount)
                        return "Transferred "+str(amount)+" GwendoBucks to "+self.bot.funcs.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"
