import random
from commands.common import CommandHelpers as CH
from commands.common import GameHelpers

bold = "\x02"
italic = "\x1D"
underline = "\x1F"
reverse = "\x16" 	# swap background and foreground colors ("reverse video")
reset = "\x0F"
blue = "\x0302"
green = "\x0303"
red = "\x0304"
grey = "\x0314"

def do_command(self, connection, event):
    cmdtype, trigger, command, replyto = CH.disect_command(self, event)
    
    # Do nothing if there is no command.
    if not command:
        return
    try:
        command.split()[0]
    except:
        return
    
    # Do noting if the games channel function is off and it's a channel message.
    if not self.db.one("SELECT games FROM channels WHERE name='" + event.target + "' AND network='" + self.network + "'") and not event.target == connection.get_nickname():
        return
    
    if command == "cmd" or command == "cmds" or command == "commands":
        if cmdtype == "cmd":
            connection.privmsg(replyto, grey + "Games: " + CH.ccc(self, "8ball") + CH.ccc(self, "dice") + CH.ccc(self, "player") + CH.ccc(self, "players") + CH.ccc(self, "levelup") + CH.ccc(self, "givecoin")[:-2] + ".")
            connection.privmsg(replyto, grey + "Game help: " + blue + self.helpchar + "level" + grey + ", " + blue + self.helpchar + "xp" + grey + ", " + blue + self.helpchar + "ap" + grey + ", " + blue + self.helpchar + "coin" + grey + ", " + blue + self.helpchar + "karma" + grey + ".")
    
    elif command.split()[0] == "8ball":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "Ask a question of the mighty and illusive 8-Ball.")
            connection.privmsg(replyto, grey + "Usage: " + blue + self.cmdchar + "8ball " + reset + italic + "question")
        elif cmdtype == "cmd":
            
            if len(command.split()) < 2:    # Command contains only !8ball.
                messages = [
                    "Don't forget to ask a question...", 
                    "Hey, that's not a question!", 
                    "What would you like to know?", 
                    "You want me to predict nothing?", 
                    "Are you intentionally not asking a question?", 
                    "Ask a question you tease!", 
                    "You do not seem to grasp this, for help type: " + blue + self.helpchar + "8ball", 
                    "You will die alone.", 
                ]
                connection.privmsg(replyto, random.choice(messages))
            else:
                messages = [
                    "Yes.", 
                    "No.", 
                    "Affirmative.",
                    "No way!", 
                    "Negative.", 
                    "Positive.", 
                    "Correct.", 
                    "Incorrect.", 
                    "Likely", 
                    "Unlikely", 
                    "Maybe.", 
                    "Definately!", 
                    "Perhaps?", 
                    "Most indubitably.", 
                    "Does the pope shit in the woods?", 
                    "When hell freezes over.", 
                    "Only between 9 and 5.", 
                    "Only just before you die.", 
                    red + bold + "ERROR: " + bold + "probability failure.", 
                    "Ask again later.", 
                    "I don't know.", 
                    "Unpredictable.", 
                ]
                connection.privmsg(replyto, random.choice(messages))
    
    elif command.split()[0] == "dice":
        if cmdtype == "help":    #Display help text.
            if len(command.split()) is not 1:
                return
            connection.privmsg(replyto, "Rolls multiple dices of chosen type. Specifying type or amount is optional.")
            connection.privmsg(replyto, grey + "Usage: " + blue + self.cmdchar + "dice " + reset + italic + "amount type")
            connection.privmsg(replyto, grey + "Example: " + blue + self.cmdchar + "dice " + reset + italic + "2 d10")
            connection.privmsg(replyto, grey + "Note: " + reset + "The dice type is specified as a " + italic + "d " + reset + "followed by the amount of sides.")
        elif cmdtype == "cmd":
            
            arguments = len(command.split()) - 1
            if arguments == 0: 
                connection.privmsg(replyto,  str(random.randint(1,  6)) + " & " + str(random.randint(1,  6)) + ".")
            elif arguments == 1:
                try:
                    diceamount = int(command.split()[1])
                except ValueError:  # Argument is not an integer.
                    if command.split()[1].startswith("d"):    # Specific dice type.
                        try:
                            dicetype = int(command.split()[1][1:])
                        except ValueError:  # "d" not followd by interger.
                            connection.privmsg(replyto, "Invalid number or type of dice. For help type: " + blue + self.helpchar + "dice" + reset + ".")
                            return
                        if dicetype < 1:
                            connection.action(replyto, "can not create objects with less then one side.")
                        else:
                            connection.privmsg(replyto, str(GameHelpers.roll_dice(1,  dicetype)[0]))
                    else:   # Argument does not start with "d" and is not an integer.
                        connection.privmsg(replyto, "Invalid number or type of dice. For help type: " + blue + self.helpchar + "dice" + reset + ".")
                    return
                if diceamount < 1:
                    connection.privmsg(replyto, "Rolling " + bold + "no " + reset + "dice.")
                elif diceamount > 10:
                    connection.action(replyto, "can not fit that many dice into it's robot hands.")
                else:
                    connection.privmsg(replyto, ", ".join(str(rolls) for rolls in GameHelpers.roll_dice(diceamount,  6)) + ".") # Roll x amount of dice.
            elif arguments == 2:
                try:
                    diceamount = int(command.split()[1])
                except ValueError:  # First argument not an integer.
                    connection.privmsg(replyto, "Invalid number of dice. For help type: " + blue + self.helpchar + "dice" + reset + ".")
                    return
                try:
                    dicetype = int(command.split()[2][1:])
                except ValueError:  # Second argument not a dice type.
                    connection.privmsg(replyto, "Invalid type of dice. For help type: " + blue + self.helpchar + "dice" + reset + ".")
                    return
                if diceamount < 1:
                    connection.privmsg(replyto, "Rolling " + bold + "no " + reset + "dice.")
                elif diceamount > 10:
                    connection.action(replyto, "can not fit that many dice into it's robot hands.")
                elif dicetype < 1:
                    connection.action(replyto, "can not create objects with less then one side.")
                elif dicetype > 9999999999 and diceamount > 1:
                    connection.action(replyto, "Those dices are so large i can only roll one at a time.")
                else:
                    connection.privmsg(replyto, ", ".join(str(rolls) for rolls in GameHelpers.roll_dice(diceamount,  dicetype)) + ".") # Roll x amount of x type dice.
            else:   # Invalid amount of arguments.
                connection.privmsg(replyto, "Too many arguments. For help type: " + blue + self.helpchar + "dice" + reset + ".")
    
    elif command.split()[0] == "player":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "Displays a users game info. User optional.")
        elif cmdtype == "cmd":
            
            if len(command.split()) == 1:
                user = event.source.nick.lower()
                message = grey + "Your info. " + reset
            elif len(command.split()) == 2:
                user = command.split()[1]
                if not self.db.one("SELECT id FROM users WHERE LOWER(name)=%s AND network='" + self.network + "'", (user, )):
                    connection.action(replyto, "does not know of a " + red + trigger.split()[1] + reset + ".")
                    return
                if user == connection.get_nickname().lower():
                    connection.privmsg(replyto, "The game does not play the master.")
                    return
                if user == event.source.nick.lower():
                    message = grey + "Your info. " + reset
                else:
                    message = grey + "Info for " + red + trigger.split()[1] + reset + ". "
            else:
                connection.privmsg(replyto, "Too many arguments, For help type " + blue + self.helpchar + "players " + reset + ".")
                return
             
            level, xp, xpspent, totalxp, karma, coin, coinspent, coingiven, apspent = GameHelpers.get_info(self, user)
            ap = xp + xpspent
            if ap < 0:
                ap = 0
            connection.privmsg(replyto, message + "Level: " + str(level) + grey + ", " + reset + "XP: " + grey + str(xpspent) + "/" + reset + str(round(xp + xpspent, 4)) + grey + ", " + reset + "AP: " + str(int(ap - float(apspent))) + grey + ", " + reset + "coin: " + str(coin) + grey + "[S " + str(coinspent) + ", G " + str(coingiven) + "], " + reset + "karma: " + str(round(karma, 4)))
    
    elif command.split()[0] == "levelup":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "Spend 10 XP per level gained. Gain multiple levels by specifying the amount.")
        elif cmdtype == "cmd":
            
            user = event.source.nick.lower()
            level, xp, xpspent, totalxp, karma, coin, coinspent, coingiven, apspent = GameHelpers.get_info(self, user)
            if len(command.split()) == 1:
                print("XP < 10: " + str(xp < 10))
                if xp < 10:
                    connection.privmsg(replyto, "Insuficcient XP, you need at least 10.")
                else:
                    self.db.run("UPDATE users SET level=level+1, xp_spent=xp_spent+10 WHERE LOWER(name)=%s AND network=%s", (user, self.network, ))
                    self.db.run("UPDATE users SET coin=coin+0.3 WHERE level>0")
            elif len(command.split()) == 2:
                try:
                    levels = int(command.split()[1])
                except:
                    connection.privmsg(replyto, "Invalid amount.")
                    return
                print("XP < level * 10: " + str(xp < levels * 10))
                if levels < 1:
                    connection.privmsg(replyto, "Invalid amount.")
                elif xp < levels * 10:
                    connection.privmsg(replyto, "Insuficcient XP, you need at least " + str(levels * 10) + ".")
                if xp - apspent < 1:
                    connection.privmsg(replyto, "Insufficient AP, you need at least 1.")
                    return
                else:
                    self.db.run("UPDATE users SET level=level+%s, xp_spent=xp_spent+%s, ap_spent=ap_spent-1 WHERE LOWER(name)=LOWER(%s) AND network=%s", (levels, levels * 10, user, self.network, ))
                    self.db.run("UPDATE users SET coin=coin+%s WHERE level>0", (self.network, ))
            else:
                connection.privmsg(replyto, "Too many arguments. For help type " + blue + self.helpchar + "levelup " + reset + ".")
    
    elif command.split()[0] == "givecoin":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "Give coins to another player. Amount optional.")
            connection.privmsg(replyto, grey + "Usage: " + blue + self.cmdchar + "givecoin " + reset + italic + "user amount")
        elif cmdtype == "cmd":
            
            if len(command.split()) == 1:
                connection.privmsg(replyto, "Insufficient arguments. For help type " + blue + self.helpchar + "givecoin" + reset + ".")
                return
            elif len(command.split()) > 3:
                connection.privmsg(replyto, "Too many arguments. For help type " + blue + self.helpchar + "givecoin" + reset + ".")
                return
            elif command.split()[1] == event.source.nick.lower():
                connection.privmsg(replyto, "You already have your own coin. For help type " + blue + self.helpchar + "givecoin" + reset + ".")
                return
                
            level, xp, xpspent, totalxp, karma, coin, coinspent, coingiven, apspent = GameHelpers.get_info(self, event.source.nick)
            receivingrecord = self.db.one("SELECT level, away FROM users WHERE LOWER(name)=%s AND network=%s", (command.split()[1], self.network, ))
            if level < 1:
                connection.privmsg(replyto, "You need to " + blue + self.cmdchar + "levelup " + reset + "to be able to give coin.")
                return
            elif coin < 1:
                connection.privmsg(replyto, "You have no coin to give.")
                return
            elif not receivingrecord:
                connection.action(replyto, "does not know of any \"" + red + trigger.split()[1] + reset + "\".")
                return
            elif receivingrecord[0] == 0:
                connection.privmsg(replyto, red + trigger.split()[1] + reset + " is not playing the game.")
                return
            elif receivingrecord[1] == True:
                connection.privmsg(replyto, red + trigger.split()[1] + reset + "is not here right now.")
                return
            elif apspent >= totalxp:
                connection.privmsg(replyto, "You have no action points, go use IRC some more...")
                return
            if len(command.split()) == 2:
                self.db.run("UPDATE users SET coin=coin-1, coin_spent=coin_spent+1, coin_given=coin_given+1, ap_spent=ap_spent+1 WHERE name=%s AND network=%s", (event.source.nick, self.network, ))
                self.db.run("UPDATE users SET coin=coin+1 WHERE LOWER(name)=%s AND network=%s", (command.split()[1], self.network, ))
            elif len(command.split()) == 3:
                self.db.run("UPDATE users SET coin=coin-%s, coin_spent=coint_spent+%s coin_given=coin_given+%s, ap_spent=ap_spent+%s WHERE name=%s AND network=%s", (command.split()[2], command.split()[2], command.split()[2], command.split()[2], event.source.nick, self.network, ))
                self.db.run("UPDATE users SET coin=coin+%s WHERE LOWER(name)=%s AND network=%s", (command.split()[2], command.split()[1], self.network))
    
    elif command.split()[0] == "players":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "Display top player rankings.")
        elif cmdtype == "cmd":
            
            toplevel = GameHelpers.list_top_players(self, "level")
            if toplevel:
                connection.notice(event.source.nick, "Ranking level: " + toplevel)
            topxp = GameHelpers.list_top_players(self, "xp_spent")
            if topxp:
                connection.notice(event.source.nick, "Ranking experience: " + topxp)
            topcoin = GameHelpers.list_top_players(self, "coin")
            if topcoin:
                connection.notice(event.source.nick, "Ranking wealth: " + topcoin)
            if not toplevel and not topxp and not topcoin:
                connection.privmsg(replyto, "Nobody is playing the game.")
    
    elif command.split()[0] == "level":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "For 10 XP you can use !levelup to gain a level. As your level increases, things become more difficult, while more capabilities and options are unlocked.")
    elif command.split()[0] == "xp":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "XP is earned by using IRC and playing the game, in channels with " + red + connection.get_nickname() + reset + ". Ask any operator in " + red + self.homechannel + reset + " to add a channel. XP is used to level up, advance classes, as a limit and as a multiplier. Once XP is expended it keeps counting towards your total.")
    elif command.split()[0] == "ap":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "XP is earned by using IRC and playing the game in channels with " + red + connection.get_nickname() + reset + ". Ask any operator in " + red + self.homechannel + reset + " to add a channel. AP is expended for every action you take in the game.")
    elif command.split()[0] == "coin":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "Coin is earned when certain events occur, for instance when a player expends XP. Coin is used to buy items and classes. To give a player coin use " + blue + self.cmdchar + "givecoin" + reset + ". Coin affects karma.")
    elif command.split()[0] == "karma":
        if cmdtype == "help":    #Display help text.
            connection.privmsg(replyto, "Karma is a secret formula, based upon on your IRC events and how you play the game. It does not increase like XP. Some events, skills and items are karma based.")
    
#    elif command.split()[0] == "classup":
#        if cmdtype == "help":    #Display help text.
#            connection.privmsg(replyto, "Spend 10 XP to gain a class in your current level. List available classes with " + blue + self.helpchar + "classup available " + reset + ".")
#            connection.privmsg(replyto, grey + "Usage: " + blue + self.cmdchar + "classup " + reset + italic + "class")
#        elif cmdtype == "cmd":
#            
#            if len(command.split()) == 1:
#                connection.privmsg(replyto, "Insufficient arguments. For help type " + blue + self.helpchar + "classup" + reset + ".")
#            if len(command.split()) == 2:
#                if command.split()[1] == "available":
#                    level, xp, xpspent, karma = GameHelpers.get_info(self, event.source.nick)
#                    if level == 0:
#                        connection.privmsg(replyto, "There are no level 0 classes.")
#                    if level == 1:
#                        connection.privmsg(replyto, "Level 1 classes: Maggot, nubcake, ")
#                    if level == 2:
#                        connection.privmsg(replyto, "Level 2 classes: Retard, ")
#                    if level == 3:
#                        connection.privmsg(replyto, "Level 3 classes: ")
#                    if level == 4:
#                        connection.privmsg(replyto, "Level 3 classes: ")
#                    if level == 5:
#                        connection.privmsg(replyto, "Level 4 classes: ")
#                else:
#            else:
#                connection.privmsg(replyto, "Too many arguments. For help type " + blue + self.helpchar + "classup" + reset + ".")
