import random
from common import font, queries


class CommandHelpers():
    def disect_command(self, event):
        trigger = event.arguments[0]    # Everything the user inputted.
        command = trigger[1:].lower()   # Command without prefix. = trigger minus first character.

        # Determine command type.
        if trigger.startswith(self.network.command_character):
            cmdtype = 'cmd'
        elif trigger.startswith(self.network.help_character):
            cmdtype = 'help'
        else:
            cmdtype = False

        # Determine where to reply to.
        if event.type == 'pubmsg':
            replyto = event.target
        elif event.type == 'privmsg':
            replyto = event.source.nick
        else:
            replyto = False

        return(cmdtype, trigger, command, replyto)

    def ccc(self, command, rights=False, event=False):   # Commandlist colour coding and channel rights filter.
        if rights:
            show = False

            if rights["homechan"] == "owner":
                if self.channels[self.network.home_channel].is_owner(event.source.nick):
                    show = True
            if rights["homechan"] == "admin":
                if self.channels[self.network.home_channel].is_owner(event.source.nick) or self.channels[self.network.home_channel].is_admin(event.source.nick):
                    show = True
            if rights["homechan"] == "oper":
                if self.channels[self.network.home_channel].is_owner(event.source.nick) or self.channels[self.network.home_channel].is_admin(event.source.nick) or self.channels[self.network.home_channel].is_oper(event.source.nick):
                    show = True
            if not event.target == self.connection.get_nickname():   # Channel message.
                if rights["chan"] == "owner":
                    if self.channels[event.target].is_owner(event.source.nick):
                        show = True
                if rights["chan"] == "admin":
                    if self.channels[event.target].is_owner(event.source.nick) or self.channels[event.target].is_admin(event.source.nick):
                        show = True
                if rights["chan"] == "oper":
                    if self.channels[event.target].is_owner(event.source.nick) or self.channels[event.target].is_admin(event.source.nick) or self.channels[event.target].is_oper(event.source.nick):
                        show = True
            if show:
                return font.blue + self.network.command_character + command + font.grey + ", "
        else:
            return font.blue + self.network.command_character + command + font.grey + ", "

# class AdminHelpers():
#     def get_channelfunctions(self, channel):
#         #channelfunctions = self.db.one("SELECT autojoin, aggressiveness, join_greeting, statistics_commands, games, chat FROM channels WHERE LOWER(name)=LOWER('" + channel + "') AND network='" + self.network + "'")
#         channelfunctions = self.db.one("SELECT autojoin FROM rotbot_channels WHERE LOWER(name)=LOWER('" + channel + "') AND network='" + self.network.id + "'")
#         if channelfunctions[0]:
#             autojoin = "on"
#         else:
#             autojoin = "off"
#         # if channelfunctions[2]:
#         #     joingreet = "on"
#         # else:
#         #     joingreet = "off"
#         # if channelfunctions[3]:
#         #     statscmds = "on"
#         # else:
#         #     statscmds = "off"
#         # if channelfunctions[4]:
#         #     games = "on"
#         # else:
#         #     games = "off"""
#         # if channelfunctions[5]:
#         #     chat = "on"
#         # else:
#         #     chat = "off"""
#         #return ("autojoin " + font.green + autojoin + font.reset + ", aggressiveness " + font.green + channelfunctions[1] + font.reset +  ", join_greeting " + font.green + joingreet + font.reset + ", statistics_commands " + font.green + statscmds + font.reset + ", games " + font.green + games + font.reset + ", chat " + font.green + chat + font.reset + ".")
#         return ('autojoin %s %s %s.' % font.green, autojoin, font.reset)
#
#     def is_channelfunction(value):
#         if value.lower() in ["autojoin", "aggressiveness", "join_greeting",  "statistics_commands",  "games", "chat"]:
#             return True
#         else:
#             return False
#
#     def describe_channelfunction(function):
#         if function == "autojoin":
#             message = "Join the channel automaticly after connecting."
#         elif function == "aggressiveness":
#             message = "How to respond to kick, ban and mode events. Options: " + font.blue + "passive" + font.reset + ", " + font.blue + "defense_only" + font.reset + ", " + font.blue + "equal_retalliation" + font.reset + ", " + font.blue + "battlebot" + font.reset + "."
#         elif function == "join_greeting":
#             message = "Greet users joining the channel on the first few joins, and later on large amounts."
#         elif function == "statistics_commands":
#             message = "Enable use of statistics commands."
#         elif function == "games":
#             message = "Enable use of game commands."
#         elif function == "chat":
#             message = "Respond to and initiate chat."
#         else:
#             message = "Sorry, this function has no description yet."
#
#         return message
#
#     def is_aggressiveness(value):
#         if value.lower() in ["passive", "defense_only", "equal_retalliation", "battlebot"]:
#             return True
#         else:
#             return False


class GameHelpers():
    def roll_dice(amount, type):
        rolls = []
        for iterations in range(amount):
            rolls.append(random.randint(1, type))
        return rolls

    def get_info(self, user):
        total_joins = queries.get_user_total_joins(self, user)
        total_kicks = queries.get_user_total_kicks(self, user)
        total_kicked = queries.get_user_total_kicked(self, user)
        total_messages = queries.get_user_total_messages(self, user)
        total_actions = queries.get_user_total_actions(self, user)
        total_notices = queries.get_user_total_notices(self, user)
        total_cursewords_added = queries.get_user_total_curseword_added(self, user)
        total_curseadjectives_added = queries.get_user_total_curseadjective_added(self, user)
        gamestats = queries.get_user_gamestats(self, user)
        xp_spent = gamestats[0]
        level = gamestats[1]
        coin = gamestats[2]
        coin_given = gamestats[3]
        coin_spent = gamestats[4]
        ap_spent = gamestats[5]
        karma_correction = gamestats[6]

        # Experience & action points.
        chat_xp = total_messages + (total_actions * 3) + (total_notices / 3)
        print('chat_xp: ' + str(chat_xp) + ' = total_messages: ' + str(total_messages) + ' + (' + str(total_actions) + ' *3) + (' + str(total_notices) + ' / 3)')
        curse_add_xp = (total_cursewords_added + total_curseadjectives_added) * 10
        print('curse_add_xp: ' + str(curse_add_xp) + ' = (total_cursewords_added:' + str(total_cursewords_added) + ' + total_curseadjectives_added:' + str(total_curseadjectives_added) + ') * 10')
        coin_xp = (coin_given * 5) + coin_spent
        print('coin_xp: ' + str(coin_xp) + ' = (coin_given:' + str(coin_given) + ' * 5) + coin_spent:' + str(coin_spent))
        total_xp = chat_xp + curse_add_xp + coin_xp + total_joins + total_kicks + total_kicked + ap_spent
        print('total_xp: ' + str(total_xp) + ' = chat_xp: ' + str(chat_xp) + ' + curse_add_xp: ' + str(curse_add_xp) + ' + coin_xp: ' + str(coin_xp) + ' + total_joins: ' + str(total_joins) + ' + total_kicks: ' + str(total_kicks) + ' + total_kicked: ' + str(total_kicked) + ' + ap_spent : ' + str(ap_spent))
        xp = (total_xp - xp_spent - (level * 2))
        print('xp :' + str(xp) + ' = (total_xp: ' + str(total_xp) + ' - xp_spent: ' + str(xp_spent) + ' - (level: ' + str(level) + ' * 100))')
        ap = (total_xp / 100) - ap_spent
        print('ap: + ' + str(ap) + ' = (total_xp: ' + str(total_xp) + ' / 100) - ap_spent: ' + str(ap_spent))

        # Karma.
        if total_xp == 0:
            total_xp = 0.01
        join_karma = total_joins / total_xp   # High value should have negative impact.
        print('join_karma: ' + str(join_karma) + ' = joins: ' + str(total_joins) + ' / total_xp: ' + str(total_xp))
        kick_karma = (total_kicks + total_kicked) / total_xp  # High value should have negative impact.
        print('kick_karma: ' + str(kick_karma) + ' = (given: ' + str(total_kicks) + ' + received: ' + str(total_kicked) + ') / total_xp:' + str(total_xp))
        shout_karma =  total_notices / total_xp # High value should have negative impact.
        print('shout_karma: ' + str(shout_karma) + ' =  total_notices: ' + str(total_notices) + ' + / total_xp: ' + str(total_xp))
        curse_add_karma = ((total_cursewords_added + total_curseadjectives_added) * 10 ) / total_xp  # High value should have positive impact.
        print('curse_add_karma: ' + str(curse_add_karma) + ' = ((total_cursewords_added: ' + str(total_cursewords_added) + ' + total_curseadjectives_added: ' + str(total_curseadjectives_added) + ') * 10 ) / total_xp: '+ str(total_xp))
        wealth_karma = (coin * 50) / total_xp
        print('wealth_karma: ' + str(wealth_karma) + ' = (coin: ' + str(coin) + ' * 50) / total_xp: ' + str(total_xp))
        charity_karma = (coin_given * 10) / total_xp
        print('charity_karma: ' + str(charity_karma) + ' = (coin_given: ' + str(coin_given) + ' * 10) / total_xp: ' + str(total_xp))
        karma =  float(karma_correction) + float(curse_add_karma) + float(charity_karma) - float(join_karma) - float(kick_karma) - float(shout_karma) - float(wealth_karma)
        print('karma: ' + str(karma) + ' =  float(karma_correction: ' + str(karma_correction) + ') + float(curse_karma: ' + str(curse_add_karma) + ') + float(charity_karma: ' + str(charity_karma) + ') - float(join_karma: ' + str(join_karma) + ') - float(kick_karma: ' + str(kick_karma) + ') - float(shout_karma: ' + str(shout_karma) + ') - float(wealth_karma: ' + str(wealth_karma) + ')')

        return level, xp, xp_spent, total_xp, karma, coin, coin_spent, coin_given, ap, ap_spent

    def player_info(self, user):
        level, xp, xp_spent, total_xp, karma, coin, coin_spent, coin_given, ap, ap_spent = GameHelpers.get_info(self, user)
        return 'Level: ' + str(level) + font.grey + ", " + font.reset + "XP: " + str(int(xp)) + "/" + font.grey + str(round(total_xp, 4)) + ", " + font.reset + "AP: " + str(int(ap)) + font.grey + ", " + font.reset + "coin: " + str(coin) + font.grey + "[S " + str(coin_spent) + ", G " + str(coin_given) + "], " + font.reset + "karma: " + str(round(karma, 4))

    def list_top_players(self, sort):
        result = queries.get_top_users(self, sort)
        if sort == "level":
            column = 1
            threshold = 0
        if sort == "xp_spent":
            column = 2
            threshold = 0
        if sort == "coin":
            column = 3
            threshold = 10
        message = ""
        for record in result:

            #if not record[column] <= threshold:

            level, xp, xp_spent, total_xp, karma, coin, coin_spent, coin_given, ap, ap_spent = GameHelpers.get_info(self, record)
            if ap < 0:
                ap = 0
            if sort == "level":
                message += font.red + str(record[0]) + font.reset + " [" + font.blue + "L " + font.green + str(level) + font.reset + ", X " + font.grey + str(xp_spent) + "/" + font.green + str(int(xp)) + font.reset + ", A " + str(int(ap)) + ", C " + font.green + str(coin) + font.reset + ", K " + font.green + str(round(karma, 2)) + font.reset + "], "
            if sort == "xp_spent":
                message += font.red + str(record[0]) + font.reset + " [L " + font.green + str(level) + font.reset + ", " + font.blue + "X " + font.grey + str(xp_spent) + "/" + font.green + str(int(xp)) + font.reset + ", A " + str(int(ap)) + ", C " + font.green + str(coin) + font.reset + ", K " + font.green + str(round(karma, 2)) + font.reset + "], "
            if sort == "coin":
                message += font.red + str(record[0]) + font.reset + " [L " + font.green + str(level) + font.reset + ", X " + font.grey + str(xp_spent) + "/" + font.green + str(int(xp)) + font.reset + ", " + font.reset + "A " + str(int(ap)) + ", " + font.blue + "C " + font.green + str(coin) + font.reset + ", K " + font.green + str(round(karma, 2)) + font.reset + "], "
        return message[:-2]
