"""Provide some commands for basic IRC functionality."""
import logging

from ircbot.lib import Plugin, has_permission
from ircbot.models import IrcChannel

log = logging.getLogger('ircbot.ircplugins.ircmgmt')


class ChannelManagement(Plugin):
    """Have IRC commands to do IRC things (join channels, quit, etc.)."""

    def start(self):
        """Set up the handlers."""
        self.connection.reactor.add_global_regex_handler(['pubmsg', 'privmsg'], r'^!join\s+([\S]+)',
                                                         self.handle_join, -20)
        self.connection.reactor.add_global_regex_handler(['pubmsg', 'privmsg'], r'^!part\s+([\S]+)',
                                                         self.handle_part, -20)
        self.connection.reactor.add_global_regex_handler(['pubmsg', 'privmsg'], r'^!quit\s*(.*)',
                                                         self.handle_quit, -20)

        super(ChannelManagement, self).start()

    def stop(self):
        """Tear down handlers."""
        self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_join)
        self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_part)
        self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_quit)

        super(ChannelManagement, self).stop()

    def handle_join(self, connection, event, match):
        """Handle the join command."""
        if has_permission(event.source, 'ircbot.manage_current_channels'):
            channel = match.group(1)
            # put it in the database if it isn't already
            chan_mod, c = IrcChannel.objects.get_or_create(name=channel, server=connection.server_config)
            log.debug("joining channel %s", channel)
            self.connection.join(channel)

            return self.bot.reply(event, "Joined channel {0:s}.".format(channel))

    def handle_part(self, connection, event, match):
        """Handle the join command."""
        if has_permission(event.source, 'ircbot.manage_current_channels'):
            channel = match.group(1)
            # put it in the database if it isn't already
            chan_mod, c = IrcChannel.objects.get_or_create(name=channel, server=connection.server_config)
            log.debug("parting channel %s", channel)
            self.connection.part(channel)

            return self.bot.reply(event, "Parted channel {0:s}.".format(channel))

    def handle_quit(self, connection, event, match):
        """Handle the join command."""
        if has_permission(event.source, 'ircbot.quit_bot'):
            self.bot.die(msg=match.group(1))


plugin = ChannelManagement