import asyncio, time
import commands.public, commands.admin, commands.games, commands.statistics, commands.chat
from common import log, queries, font
from events.common import Inform


def process_event(self, connection, event):
    log.info(event) # Log to console.

    # Ignore server connect messages.
    if event.source == None:
        return

    # Get and update resources.
    user = queries.create_or_get_and_update_last_event(self, 'user', 'pn', user_name=event.source.nick, event_subject_name=event.target)
    channel = None

    # 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)

    if event.source.nick == connection.get_nickname():  # Message came from myself.
        return
    elif event.source.nick == "NickServ":   # Message from NickServ.
        if event.arguments[0].startswith("This nickname is registered"):
            connection.privmsg('NickServ', 'identify %s %s' % (self.network.nickname, self.network.password)) # Identify with NickServ. Also doing it on_welcome, but if there is a netsplit or so and there is no welcome, but a need to login, this is needed.
            return
        elif event.arguments[0].endswith(' is not a registered nickname.') or event.arguments[0].startswith('Nick ') and event.arguments[0].endswith(' isn\'t registered.') or event.arguments[0] == 'Your nick isn\'t registered.': # Username from database is not registered.
            log.info('Registerring with NickServ.')
            Inform.operators(self, connection, 'Regisring %s%s%s with %sNickServ%s.' % (font.red, self.network.nickname, font.reset, font.red, font.reset))
            connection.privmsg('NickServ', 'register %s spamtBK@xs4all.nl' % (self.network.password)) # Register with NickServ.
            return
        elif event.arguments[0].startswith('Nickname ') and event.arguments[0].endswith('registered.') or event.arguments[0].startswith('Nickname ') and ' registered under your account: *' in event.arguments[0]:
            Inform.home_channel(self, connection, 'Registerred nickname %s%s%s with NickServ, adjusting settigns.' % font.red, self.network.nickname, font.reset)
            connection.privmsg('NickServ', 'ACCESS LIST')
            connection.privmsg('NickServ', 'AJOIN ADD %s' % (self.network.home_channel, queries.get_channel_key(self, self.network.home_channel)))
            connection.privmsg('NickServ', 'SET AUTOOP ON')
            connection.privmsg('NickServ', 'SET HIDE EMAIL ON')
            connection.privmsg('NickServ', 'SET KILL QUICK')
            connection.privmsg('NickServ', 'SET SECURE ON')
            connection.privmsg('NickServ', 'SET URL %snetwork/%s' % (self.webgui['base_url'], self.network.slug))
            return
        elif event.arguments[0].startswith('You must have been using this nick for at least 30 seconds to register.'):
            log.info('Waiting 31 seconds to register with NickServ.')
            asyncio.run(register_later(self, connection, 31))
            return
        elif event.arguments[0].startswith("You are already identified."):
            return
        elif event.arguments[0].startswith('nick, type ') and '/msg NickServ IDENTIFY ' in event.arguments[0] and event.arguments[0].endswith(' Otherwise,'):
            return
        elif event.arguments[0].startswith("please choose a different nick."):
            return
        elif event.arguments[0] == 'Password accepted - you are now recognized.':
            return
    elif event.source.nick == "ChanServ":
        if event.arguments[0].startswith("Key for channel ") and len(event.arguments[0]) > 5:   # Received channel key.
            log.info('Saving channel password received from NickServ for: %s' % event.arguments[0].split(' ')[3])
            queries.save_channel_key(self, event.arguments[0].split(' ')[3], event.arguments[0].split(' ')[5][:-1])
            connection.join(event.arguments[0].split(' ')[3], event.arguments[0].split(' ')[5][:-1])
            Inform.owners(self, connection, "Received " + red + event.arguments[0].split(" ")[3] + reset + " key: " + event.arguments.split(" ")[5][:-1])
            returnZZ
        elif event.arguments[0] == "Password authentication required for that command.":  # Not authenticated with NisckServ.
            connection.privmsg('NickServ', 'identify %s %s' % (self.network.nickname, self.network.password))
            Inform.notice_owners(self, connection, "Not authenticated with NickServ.")
            return
        elif event.arguments[0].startswith("You have been unbanned from ") or event.arguments[0].endswith(" autokick list is empty.") or event.arguments[0].startswith("You are already in ") or event.arguments[0] == "Syntax: UNBAN channel [nick]" or event.arguments[0] == "/msg ChanServ HELP UNBAN for more information":
            return
        # if event.arguments[0].startswith("Channel ") and event.arguments[0].endswith(" has no key."):
        #     return
    if event.source.nick != "Global":
        Inform.notice_owners(self, connection, 'Notice from %s%s%s: %s%s' % (font.red, event.source.nick, font.grey, font.reset, event.arguments[0]))
    if event.arguments[0] == '*** Looking up your hostname...' or event.arguments[0] == '*** Found your hostname' or event.arguments[0].startswith('*** Connected securely via ') or event.arguments[0] == '*** Your host is masked (' or event.arguments[0] == 'You are connected to ' or event.arguments[0] == 'Highest connection count: ':
        return  # Do not forward these messages.

async def register_later(self, connection, seconds):
    await asyncio.sleep(seconds)
    connection.privmsg('NickServ', 'identify %s %s' % (self.network.nickname, self.network.password))
