from datetime import datetime
from common import font, queries
from commands.common import CommandHelpers as CH


def do_command(self, connection, event, user, channel):
    cmdtype, trigger, command, replyto = CH.disect_command(self, event)

    # Do nothing if it's not a type of command.
    if not cmdtype:
        return

    # Do nothing if there is no command.
    if not command:
        return

    # The first word of the command sting with arguments, is just the command without arguments.
    try:
        one = command.split()[0]    # Get raw command.
    except:
        return

    # Do noting if the statistics channel function is off and it's a channel message.
    if not event.target == connection.get_nickname():
        if not queries.get_channel_setting_statistic_commands(self, event.target):
            return

    if command == 'cmd' or command == 'cmds' or command == 'commands':
        if cmdtype == 'cmd':
            connection.privmsg(replyto, '%sStatistics: %s' % (font.grey, CH.ccc(self, "stat")[:-2] + ".")) #CH.ccc(self, "seen") + CH.ccc(self, "joins") + CH.ccc(self, "kicks") + CH.ccc(self, "messages") + CH.ccc(self, "actions") + CH.ccc(self, "notices")[:-2] + "."))


    elif one == 'stat' or one == 'stats' or one == 'statistic' or one == 'statistics':
        if len(command.split()) == 1:   # Command without arguments.
            if cmdtype == 'help':
                connection.privmsg(replyto, 'Serves a link with statistics on a channel or username. Channel and user arguments are optional')
                connection.privmsg(replyto, 'Usage %s%s%s %s%schannel' % (font.blue, self.network.command_character, one, font.reset, font.italic))
                if channel: # Don't advertise our channel on other channels.
                    connection.privmsg(replyto, '%sExample %s%s%s %s%s' % (font.grey, font.reset, event.target, one, self.network.home_channel))
                else:
                    connection.privmsg(replyto, '%sExample %s%s%s %s%s' % (font.grey, font.reset, self.network.command_character, one, self.network.home_channel))
            else:   # Actual command with no aruments.
                if not channel:   # Command sent directly to bot
                    connection.privmsg(replyto, '%sYour statistics:%s %suser/%s' % (font.grey, font.reset, self.webgui.base_url, user.slug))
                else:   # Command sent to channel
                    connection.privmsg(replyto, '%sChannel statistics:%s %channel/%s %sYour statistics:%s %suser/%s' % (font.grey, font.reset, self.webgui.base_url, channel.slug, font.grey, font.reset, self.webgui.base_url, user.slug))

        elif len(command.split()) == 2:   # Command with one argument.
            if command.split()[1] in self.channels: # Argument matches a inhabited channel.
                if cmdtype == 'help':
                    connection.privmsg(replyto, 'Send a link for statistics on channel: %s%s' % ( font.red, command.split()[1]))
                else:   # Actual command with one argument
                    channel_slug = queries.get_channel_slug(self, command.split()[1])
                    connection.privmsg(replyto, '%sStatistics on channel %s%s%s:%s %schannel/%s' % (font.grey, font.red, command.split()[1], font.grey, font.reset, self.webgui.base_url, channel_slug))
            else:   # Argument does not match a channel.
                user_slug = queries.get_user_slug(self, command.split()[1])
                if user:
                    connection.privmsg(replyto, '%sStatistics on nickname %s%s%s:%s %s/user/$s' % (font.grey, font.red, command.split()[1], font.grey, font.reset, self.webgui.base_url, user_slug))
                else:   # Argument does not match a channel or user.
                    connection.privmsg(replyto, 'I have not had the pleasure of being aquinted with: %s%s' % (font.red, command.split()[1]))

        elif len(command.split()) >= 3: # Too many arguments.
            connection.privmsg('Too many arguments, for help type: %s%s%s' % (font.blue, self.network.command_character, one))



    # elif command.split()[0] == "joins" or command.split()[0] == "kicks" or command.split()[0] == "messages" or command.split()[0] == "actions" or command.split()[0] == "notices":
    #     if cmdtype == "help":    #Display help text.
    #         if len(command.split()) != 1:
    #             return
    #         connection.privmsg(replyto, "Display amount of " + command.split()[0] + " of user and channel. Channel and user optional.")
    #         connection.privmsg(replyto, grey + "Usage: " + blue + self.cmdchar + command.split()[0] + " " + font.reset + font.italic + "channel user")
    #     elif cmdtype == "cmd":
    #
    #         # Parse user input
    #         user = event.source.nick
    #         channel = None
    #         channelonly= False
    #         if not connection.get_nickname() == event.target:   # Channel message.
    #             channel = event.target
    #         if len(command.split()) == 1:    # Command contains only !joins.
    #             user = event.source.nick
    #         elif len(command.split()) == 2:  # Command has one argument.
    #             if command.split()[1] in self.channels:
    #                 channel = command.split()[1]
    #                 if connection.get_nickname() == event.target:   # Private message.
    #                     channelonly = True
    #             else:
    #                 user = trigger.split()[1]
    #         elif len(command.split()) == 3: # Command has two arguments.
    #             if not command.split()[1] in self.channels: # Bot does not inhabit requested channel.
    #                 if not command.split()[2] in self.channels: # User did not revert channel and user in command syntax.
    #                     connection.action(replyto, "does not inhabit " + font.red + command.split()[1] + font.reset + ".")
    #                     return
    #                 else:   # User reverted user and channel in command syntax.
    #                     user = trigger.split()[1]
    #                     channel = command.split()[2]
    #             else: # Bot does inhabit requested channel.
    #                 user = trigger.split()[2]
    #                 channel = trigger.split()[1]
    #         elif len(command.split()) < 5:  # To many arguments
    #             connection.privmsg(replyto, "To many arguments. For help type " + blue + self.helpchar + "joins" + font.reset + ".")
    #             return
    #
    #         if command.split()[0] == "joins":
    #             if channel: # User and channel.
    #                 userstat = str(sum(self.db.all("SELECT " + command.split()[0] + " FROM " + command.split()[0] + " WHERE channel_network='" + self.network + "' AND LOWER(\"user\")=LOWER('" + user + "') AND user_network='" + self.network + "'")))
    #                 userchannelstat = str(self.db.one("SELECT " + command.split()[0] + " FROM " + command.split()[0] + " WHERE LOWER(channel)=LOWER('" + channel + "') AND channel_network='" + self.network + "' AND LOWER(\"user\")=LOWER('" + user + "') AND user_network='" + self.network + "'"))
    #                 channelstat = str(sum(self.db.all("SELECT " + command.split()[0] + " FROM " + command.split()[0] + " WHERE LOWER(channel)=LOWER('" + channel + "') AND channel_network='" + self.network + "' AND user_network='" + self.network + "'")))
    #                 if userchannelstat == "None":
    #                     userchannelstat = "0"
    #                 if channelonly:
    #                     connection.privmsg(replyto, font.red + channel + font.reset + " has " + green + channelstat + font.reset + " " + command.split()[0] + font.reset + " in total.")
    #                 elif userstat == "0" and not channelonly: # No user joins on record.
    #                     connection.action(replyto, "has no record of any joins by " + font.red + user + font.reset + " in " + font.red + channel + font.reset + ".")
    #                 else:   # User joins on record.
    #                     connection.privmsg(replyto, font.red + user + font.reset + " has " + green + userstat + font.reset + " " + command.split()[0] + ". Of which " + green + userchannelstat + font.reset + " have been in " + font.red + channel + font.reset + ", that has " + green + channelstat + font.reset + " " + command.split()[0] + font.reset + " in total.")
    #             else:   # Only user.
    #                 userstat = str(sum(self.db.all("SELECT " + command.split()[0] + " FROM " + command.split()[0] + " WHERE channel_network='" + self.network + "' AND LOWER(\"user\")=LOWER('" + user + "') AND user_network='" + self.network + "'")))
    #                 if userstat == "0":    # No statistics on user.
    #                     connection.action(replyto, "has no record of any joins by " + font.red + user + font.reset + ".")
    #                 else:   # Got statistics on user.
    #                     connection.privmsg(replyto, font.red + user + font.reset + " has " + green + userstat + font.reset + " " + command.split()[0] + " in channels I monitor.")
    #         elif command.split()[0] == "kicks":
    #             if channel: # User and channel.
    #                 try:
    #                     givenkicks, receivedkicks = self.db.one("SELECT given, received FROM " + command.split()[0] + " WHERE LOWER(channel)=LOWER('" + channel + "') AND channel_network='" + self.network + "' AND LOWER(\"user\")=LOWER('" + user + "') AND user_network='" + self.network + "'")
    #                 except:
    #                     givenkicks = 0
    #                     receivedkicks = 0
    #                 if channelonly:
    #                     connection.privmsg(replyto, font.red + channel + font.reset + " has " + green + channelstat + font.reset + " " + command.split()[0] + font.reset + " in total.")
    #                 elif givenkicks == 0 and receivedkicks == 0:  # No kicks on record.
    #                     connection.action(replyto, "has no record of any kicks for " + font.red + user + font.reset + " in " + font.red + channel + font.reset + ".")
    #                 else:   # Kciks on record.
    #                     channelkicks = self.db.all("SELECT given FROM " + command.split()[0] + " WHERE LOWER(channel)=LOWER('" + channel + "') AND channel_network='" + self.network + "'")
    #                     connection.privmsg(replyto, font.red + user + font.reset + " has kicked " + green + str(givenkicks) + font.reset + " and been kicked " + green + str(receivedkicks) + font.reset + " times in " + font.red + channel + font.reset + ", where were " + green + str(sum(channelkicks)) + font.reset + " kicks in total.")
    #             else:   # Only user.
    #                 userstat = self.db.all("SELECT given, received FROM kicks WHERE LOWER(\"user\")=LOWER('" + user + "') AND user_network='" + self.network + "'")
    #                 kicksgiven = 0
    #                 kicksreceived = 0
    #                 for record in userstat:
    #                     kicksgiven += record[0]
    #                     kicksreceived += record[1]
    #                 if kicksgiven == 0 and kicksreceived == 0:
    #                     connection.action(replyto, font.red + user + font.reset + " has no record of any kicks for " + font.red + user + font.reset + " in " + font.red + channel + font.reset + ".")
    #                 else:
    #                     connection.privmsg(replyto, font.red + user + font.reset + " has given " + green + str(kicksgiven) + font.reset + " and received " + green + str(kicksreceived) + font.reset + " kicks")
    #         elif command.split()[0] == "messages" or command.split()[0] == "actions" or command.split()[0] == "notices":
    #             userstat = self.db.all("SELECT " + command.split()[0] + ", " + command.split()[0] + "_words, " + command.split()[0] + "_characters FROM messages WHERE LOWER(\"user\")=LOWER('" + user + "') AND user_network='" + self.network + "'")
    #
    #             userrecord = False
    #             for record in userstat:
    #                 if not record[0] == 0:
    #                     userrecord = True
    #
    #             if not userrecord:
    #                 if command.split()[0] == "messages":
    #                     connection.action(replyto, "has no record of " + font.red + user + font.reset + " speaking.")
    #                     return
    #                 if command.split()[0] == "actions":
    #                     connection.action(replyto, "has no record of " + font.red + user + font.reset + " acting.")
    #                     return
    #                 if command.split()[0] == "notices":
    #                     connection.action(replyto, "has not noticed " + font.red + user + font.reset + ".")
    #                     return
    #             messages, words, characters = StatisticsHelpers.add_message_stats(userstat)
    #             message = "Totals of " + font.red + user + " " + green + str(messages) + font.reset + " " + blue + command.split()[0] + font.reset + ", " + green + str(words) + font.reset + " words, " + green + str(characters) + font.reset + " characters."
    #             if channel: # User and channel.
    #                 userchanstat = self.db.one("SELECT " + command.split()[0] + ", " + command.split()[0] + "_words, " + command.split()[0] + "_characters FROM messages WHERE lower(channel)=lower('" + channel + "') AND channel_network='" + self.network + "' AND lower(\"user\")=lower('" + user + "') AND user_network='" + self.network + "'")
    #                 chanstat = self.db.all("SELECT " + command.split()[0] + ", " + command.split()[0] + "_words, " + command.split()[0] + "_characters FROM messages WHERE lower(channel)=lower('" + channel + "') AND channel_network='" + self.network + "'")
    #                 if not userchanstat[0] == 0:
    #                     message += " " + font.red + user + font.reset + " in " + font.red + channel + " " + green + str(userchanstat[0]) + font.reset + " " + blue + command.split()[0] + font.reset + ", " + green + str(userchanstat[1]) + font.reset + " words, " + green + str(userchanstat[2]) + font.reset + " chars."
    #                 channelrecord = False
    #                 for record in chanstat:
    #                     if not record[0] == 0:
    #                         channelrecord = True
    #                 if channelrecord:
    #                     messages, words, characters = StatisticsHelpers.add_message_stats(chanstat)
    #                     message += " Total in " + font.red + channel + " " + green + str(messages) + font.reset + " " + blue + command.split()[0] + font.reset + ", " + green + str(words) + font.reset + " wrd, " + green + str(characters) + font.reset + " chr."
    #             connection.privmsg(replyto, message)
    #
    # elif command.split()[0] == "seen":
    #     if cmdtype == "help":    #Display help text.
    #         if len(command.split()) != 1:
    #             return
    #         connection.privmsg(replyto, "Report the last sighting of a user.")
    #         connection.privmsg(replyto, grey + "Usage: " + blue + self.cmdchar + command.split()[0] + " " + font.reset + font.italic + "user")
    #     elif cmdtype == "cmd":
    #
    #         if len(command.split()) == 1:
    #             connection.privmsg(replyto, "I am seeing you right now. For help type " + blue + self.helpchar + font.reset + ".")
    #         elif len(command.split()) == 2:
    #             if not self.db.one("SELECT last_act_type FROM users WHERE LOWER(name)='" + command.split()[1] + "' AND network='" + self.network + "'"):
    #                 connection.action(replyto, "has never seen " + font.red + trigger.split()[1] + font.reset + ".")
    #             elif command.split()[1] == event.source.nick.lower():
    #                 connection.action(replyto, "holds up a mirror to " + event.source.nick + ".")
    #             elif "!" in command.split()[1] and "@" in command.split()[1]:
    #                 connection.privmsg(replyto, "The looks more like a hostname then a nickname to me.")
    #             else:
    #                 record = self.db.one("SELECT last_act_type, last_act_datetime, last_act_channel, last_act, last_act_auxiliary, away, away_reason FROM users WHERE LOWER(name)='" + command.split()[1] + "' AND network='" + self.network + "'")
    #                 if command.split()[1] == connection.get_nickname().lower():
    #                     action = "last action was "
    #                 else:
    #                     action = "last saw " + font.red + trigger.split()[1] + font.reset + " "
    #                 if record[0] == "nick":
    #                     action += "changing nickname to " + font.red + record[3]
    #                 elif record[0] == "join":
    #                     action += "joining " + font.red + record[2]
    #                 elif record[0] == "kick":
    #                     if record[4]:
    #                         action += "kicking " + font.red + record[4] + font.reset + " for " + green + record[3]
    #                     else:
    #                         action += "kicking " + font.red + record[3]
    #                 elif record[0] == "kicked":
    #                     if record[4]:
    #                         action += "being kicked by " + font.red + record[3] + font.reset + " for " + green + record[4]
    #                     else:
    #                         action += "being kicked by " + font.red + record[3]
    #                 elif record[0] == "mode":
    #                     action += "changing modes on " + font.red + record[3]
    #                 elif record[0] == "part":
    #                     action += "parting " + font.red + record[2]
    #                     if record[3]:
    #                         action += font.reset + " for " + record[3]
    #                 elif record[0] == "quit":
    #                     action += "disconnecting"
    #                     if record[3]:
    #                         action += " due to " + green + record[3]
    #                 elif record[0] == "topic":
    #                     action += "changing the topic of " + font.red + record[2] + font.reset + " to " + green + record[3]
    #                 elif record[0] == "msg":
    #                     action += "posting " + green + record[3] + font.reset + " to " + font.red + record[2]
    #                 elif record[0] == "notice":
    #                     action += "posting the notice " + green + record[3] + " to " + font.red + record[2]
    #                 elif record[0] == "action":
    #                     action += green + record[3] + font.reset + " in " + font.red + record[2]
    #                 else:
    #                     connection.privmsg(replyto, "Last stored action unsupported by command code.")
    #                     return
    #                 action += font.reset + ", "
    #                 differential = datetime.now() - record[1]
    #                 if differential.seconds < 5:    # Less then 5 seconds.
    #                     action += blue + "right now."
    #                 elif differential.seconds < 20: # Less then 20 seconds.
    #                     action += blue + "just now."
    #                 elif differential.seconds < 60: # Less then a minute.
    #                     action += green + str(differential.seconds) + blue + " seconds " + font.reset + "ago."
    #                 elif differential.seconds / 60 == 1: # 1 minute.
    #                     action += green + "1 " + blue + "minute " + font.reset + "ago."
    #                 elif int(differential.seconds / 60) < 60:   # Less then an hour.
    #                     action += green + str(int(differential.seconds / 60)) + blue + " minutes " + font.reset + "ago."
    #                 elif int(differential.seconds / 60) ==  60: # 1 hour.
    #                     action += green + "1 " + blue + "hour " + font.reset + "ago."
    #                 elif int(differential.seconds / 3600) < 24 : # Less then a day.
    #                     remaining_seconds = int(differential.seconds - int(differential.seconds / 3600) * 3600)
    #                     action += green + str(int(differential.seconds / 3600)) + blue + " hours" + font.reset + " and " + str(int(remaining_seconds / 60)) + " minutes ago."
    #                 elif int(differential.seconds / 3600) == 24 : # 1 day.
    #                     action += green + "1 " + blue + "day " + font.reset + "ago."
    #                 elif differential.days < 7: # Less then a week.
    #                     remaining = differential - datetime.timedelta(days=differential.days)
    #                     action += green + str(differential.days) + blue + " days " + font.reset + "and " + str(int(remaining.seconds / 3600)) + " hours ago."
    #                 elif differential.days < 365:   # Less then a year.
    #                     action += green + str(differential.days) + blue + " days " + font.reset + "ago."
    #                 elif differential.days < 365:   # Less then 5 years.
    #                     remaining_days = int(int(differential.days / 365) * 365)
    #                     remaining = differential - datetime.timedelta(days=remaining_days)
    #                     action += green + str(int(differential.days / 365)) + blue + " years " + font.reset + "and " + str(remaining.days) + " days."
    #                 else:   # More then 5 years.
    #                     action += green + str(int(differential.days / 365)) + blue + " years ago."
    #                 connection.action(replyto, action)
    #                 if record[5]:
    #                     if record[6]:
    #                         connection.privmsg(replyto, font.red + trigger.split()[1] + font.reset + " is away " + green + record[6] + ".")
    #                     else:
    #                         connection.privmsg(replyto, font.red + trigger.split()[1] + font.reset + " is away.")
    #         else:   # Too many arguments.
    #             connection.privmsg(replyto, "Too many arguments. For help type " + blue + self.helpchar + "seen" + font.reset + ".")
