from __future__ import absolute_import
import signal
import bot
from db import session
from models import Nick, History
from nicks import Nicks, NickNotFound

# set up signal handling
def speak_bot(signum, frame):
    bot = bot.Bot.factory()
    bot.be_quiet = False

signal.signal( signal.SIGALRM, speak_bot )

class BotCtrl(object):
    # Default available commands to our bot friend
    # Commands require the nick as the first argument and must be authorized

    def __init__(self):
        self.bot = bot.Bot.factory()
    
    # admin commands
    def shutdown(self,nick,*args):
        if nick.is_privileged():
            return self.bot.shutdown()

        return self._unauthorized(nick)

    def promote(self,nick,*args):
        if nick.is_privileged():
            try:
                pnick = Nicks().get_by_name(args[0])
                pnick.promote()
                return 'Added bot wrangler {}'.format(pnick.name)

            except IndexError:
                return 'Sorry but I need a name to promote'
            except NickNotFound:
                return 'Sorry, I don\'t know {}'.format(args[0])

        return self._unauthorized(nick)

    def demote(self,nick,*args):
        if nick.is_privileged():
            try:
                pnick = Nicks().get_by_name(args[0])
                pnick.demote()
                return 'Removed {} as a bot wrangler.'.format(pnick)
            except IndexError:
                return 'Sorry but I need a name to demote.'
            except NickNotFound:
                return 'Sorry, I don\'t know {}'.format(args[0])

        else:
            return self._unauthorized(nick)

    def _unauthorized(self, nick):
        return 'I can\'t let you do that {}'.format(nick.name)

    # base commands
    def remember(self,nick,*args):
        srchnick = args[0]
        if len(args) == 2:
            # remembering a history line, usually a silly thing someone said
            srchnick, pattern = args
            try:
                srchnick_o = Nicks().get_by_name(srchnick)
            
                nicklines = self.bot.mem.find_in_history(nick=srchnick_o, phrase=pattern)

                self.bot.mem.remember(srchnick_o.name, nicklines[0].line, added_by=nick)

                return "Ok {}, remembering \"{}\"".format(nick.name, l[1])
            except NickNotFound:
                return "Sorry, I don't know who {} is".format(srchnick)

        elif len(args) > 2:
            # remembering a phrase
            verb = re.sub('[<>]','',args[1])
            self.bot.mem.remember(args[0], ' '.join(args[2]), added_by=nick, verb=verb)
            return "Ok {}".format(nick)

    def forget(self,nick,*args):
        command = args[0]
        phrase,resp = command.split(' ')
        po = self.bot.mem.get_phrase_by_text(phrase)

        if resp:
            resp_o = self.bot.mem.get_response_by_text(resp)
            po.responses.remove(resp_o)
        else:
            po.forget()

        session.commit()
        return "Ok {}".format(nick)

    def whatwasthat(self,nick,*args):
        output = self.bot.get_last()
        return "That was: {}".format(output)
        
    def quiet(self,nick,*args):
        self.bot.quiet_timer += config.quiet_period

        if self.bot.quiet_timer > config.quiet_max:
            self.bot.quiet_timer = config.quiet_period

        self.bot.be_quiet = True
        signal.alarm( self.bot.quiet_timer )
        return "OK {}, I'll be quiet for the next {} seconds".format(nick.name, self.bot.quiet_timer)

# uses tuples. Instance will be created then getattr called on the string to execute the method
command_tokens = {}
rules = {}

command_tokens['shutdown'] = (BotCtrl,'shutdown')
command_tokens['promote'] = (BotCtrl,'promote')
command_tokens['demote'] = (BotCtrl,'demote')
command_tokens['remember'] = (BotCtrl,'remember')
command_tokens['forget'] = (BotCtrl,'forget')
command_tokens['whatwasthat'] = (BotCtrl,'whatwasthat')
command_tokens['quiet'] = (BotCtrl,'quiet')

rules['^shutdown'] = 'shutdown'
rules['^promote ([^\s]+)$'] = 'promote'
rules['^demote ([^\s]+)$'] = 'demote'
rules['^remember ([^\s]+) (.+)$'] = 'remember'
rules['^(.+?) (is|<[^>]+>) (.+)'] = 'remember'
rules['^forget (.+)$'] = 'forget'
rules['^what.?was.?that\??'] = 'whatwasthat'
rules['^(be\s+quiet|quiet|shut.?up|shuddap)'] = 'quiet'
