import datetime, pytz
import commands.public, commands.admin, commands.games, commands.statistics, commands.chat
from common import log, queries


def process_event(self, connection, event):
    # Let's not log all public messages to the console.

    # Get and update resources.
    channel = queries.create_or_get_and_update_last_event(self, 'channel', 'cm', channel_name=event.target, user_name=event.source.nick)
    user = queries.create_or_get_and_update_last_event(self, 'user', 'cm', channel_name=event.target, user_name=event.source.nick)
    queries.update_message_statistics(self, 'message', channel.id, user.id)   # Update message statistics

    # Respond to commands.
    commands.public.do_command(self, connection, event, user, channel)
    commands.games.do_command(self, connection, event, user, channel)
    commands.statistics.do_command(self, connection, event, user, channel)
    commands.chat.do_command(self, connection, event, user, channel)
    commands.admin.do_command(self, connection, event, user, channel)

    # Stop if channelfunction chat if off.
    if not queries.get_channel_setting_chat(self, channel.id):
        return

    # if connection.get_nickname().lower() in event.arguments[0].lower() and event.source.nick is not connection.get_nickname(): # Bot's name was mentioned
    #     if event.arguments[0].startswith(self.cmdchar):
    #         return  # Stop if it's a command.
    #     Replyto.name(connection, event)

    # Character lame.
    elif event.arguments[0] == len(event.arguments[0]) * event.arguments[0][0]:   # Trigger exclusively same character.

        # Stop if it's short and not a dot or exclematin mark,
        if len(event.arguments[0]) < 3:
            if event.arguments[0][0] not in ['.', '!']:
                return

        # Stop if it's long.
        if len(event.arguments[0]) > 20:
            return

        # Stop if lamed recently.
        timeout = 10    # Timeout in minutes.
        chan_lastlame = queries.get_channel_last_lame(self, channel.id)
        user_lastlame = queries.get_user_last_lame(self, user.id)
        timezone = pytz.timezone('Europe/Amsterdam')
        if user_lastlame and user_lastlame > timezone.localize(datetime.datetime.now()) - datetime.timedelta(minutes=timeout):  # Lamed user recently.
            return

        # Do not say KKK.
        if event.arguments[0] == "kk":
            return

        connection.privmsg(event.target, event.arguments[0] + event.arguments[0][:1])

        # Update lastlame.
        queries.update_channel_last_lame(self, channel.id)
        queries.update_user_last_lame(self, user.id)
