"""
IrcAdmin - handle normal IRC functions one would expect
Copyright (C) 2010  Brian S. Stephan

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from ConfigParser import NoOptionError
import signal
import sys

from extlib import irclib

from Module import Module

class IrcAdmin(Module):

    """Support miscellaneous IRC stuff --- joining channels, changing the nick, etc."""

    def register_handlers(self, server):
        server.add_global_handler('welcome', self.on_connect, self.priority())

    def unregister_handlers(self):
        self.server.remove_global_handler('welcome', self.on_connect)

    def on_connect(self, connection, event):
        """Set up handlers when the bot has connected to IRC."""

        # user modes
        try:
            nick = self.config.get('dr.botzo', 'nick')
            usermode = self.config.get('dr.botzo', 'usermode')
            connection.mode(nick, usermode)
        except NoOptionError: pass

        # join the specified channels
        try:
            autojoins = self.config.get(self.__class__.__name__, 'autojoin').split(',')
            for channel in autojoins:
                if irclib.is_channel(channel):
                    connection.join(channel)
        except NoOptionError: pass

    def do(self, connection, event, nick, userhost, what, admin_unlocked):
        """Try all the admin methods."""

        # TODO: sophisticate. also, document all of these

        whats = what.split(' ')

        if whats[0] == '!join' and admin_unlocked and len(whats) >= 2:
            return self.sub_join_channel(connection, event, nick, userhost, what, admin_unlocked)
        elif whats[0] == '!part' and admin_unlocked and len(whats) >= 2:
            return self.sub_part_channel(connection, event, nick, userhost, what, admin_unlocked)
        elif whats[0] == '!quit' and admin_unlocked:
            return self.sub_quit_irc(connection, event, nick, userhost,  what, admin_unlocked)
        elif whats[0] == '!autojoin' and admin_unlocked and len(whats) >= 3:
            return self.sub_autojoin_manipulate(connection, event, nick, userhost, what, admin_unlocked)
        elif whats[0] == '!save' and admin_unlocked:
            self.irc.save_modules()
            self.irc.save_config()
            return 'Saved.'
        elif whats[0] == '!nick' and admin_unlocked and len(whats) >= 2:
            return self.sub_change_nick(connection, event, nick, userhost, what, admin_unlocked)
        elif whats[0] == '!load' and admin_unlocked and len(whats) >= 2:
            return self.sub_load_module(connection, event, nick, userhost, what, admin_unlocked)
        elif whats[0] == '!reload' and admin_unlocked and len(whats) >= 2:
            return self.sub_reload_module(connection, event, nick, userhost, what, admin_unlocked)
        elif whats[0] == '!unload' and admin_unlocked and len(whats) >= 2:
            return self.sub_unload_module(connection, event, nick, userhost, what, admin_unlocked)
        elif whats[0] == '!modules':
            return self.sub_list_modules(connection, event, nick, userhost, what, admin_unlocked)

    def sub_join_channel(self, connection, event, nick, userhost, what, admin_unlocked):
        whats = what.split(' ')

        channel = whats[1]
        if irclib.is_channel(channel):
            connection.join(channel)
            replystr = 'Joined ' + channel + '.'
            return replystr

    def sub_part_channel(self, connection, event, nick, userhost, what, admin_unlocked):
        whats = what.split(' ')

        channel = whats[1]
        if irclib.is_channel(channel):
            connection.part(channel, ' '.join(whats[2:]))
            replystr = 'Parted ' + channel + '.'
            return replystr

    def sub_quit_irc(self, connection, event, nick, userhost, what, admin_unlocked):
        whats = what.split(' ')
        self.irc.quit_irc(connection, ' '.join(whats[1:]))

    def sub_autojoin_manipulate(self, connection, event, nick, userhost, what, admin_unlocked):
        whats = what.split(' ')

        if whats[1] == 'add':
            try:
                # get existing list
                channel = whats[2]
                if irclib.is_channel(channel):
                    channelset = set(self.config.get(self.__class__.__name__, 'autojoin').split(','))
                    channelset.add(channel)
                    self.config.set(self.__class__.__name__, 'autojoin', ','.join(channelset))
                    replystr = 'Added ' + channel + ' to autojoin.'
                    return replystr
            except NoOptionError: pass
        elif whats[1] == 'remove':
            try:
                # get existing list
                channel = whats[2]
                if irclib.is_channel(channel):
                    channelset = set(self.config.get(self.__class__.__name__, 'autojoin').split(','))
                    channelset.discard(channel)
                    self.config.set(self.__class__.__name__, 'autojoin', ','.join(channelset))
                    replystr = 'Removed ' + channel + ' from autojoin.'
                    return replystr
            except NoOptionError: pass

    def sub_change_nick(self, connection, event, nick, userhost, what, admin_unlocked):
        whats = what.split(' ')

        newnick = whats[1]
        connection.nick(newnick)
        self.config.set('dr.botzo', 'nick', newnick)
        replystr = 'changed nickname'
        return replystr

    def sub_load_module(self, connection, event, nick, userhost, what, admin_unlocked):
        """Load a module (in both the python and dr.botzo sense) if not
        already loaded.
        """

        whats = what.split(' ')
        return self.irc.load_module(whats[1])

    def sub_unload_module(self, connection, event, nick, userhost, what, admin_unlocked):
        """Attempt to unload and del a module if it's loaded."""

        whats = what.split(' ')
        return self.irc.unload_module(whats[1])

    def sub_reload_module(self, connection, event, nick, userhost, what, admin_unlocked):
        """Attempt to reload a module, by removing it from memory and then
        re-initializing it.
        """

        whats = what.split(' ')
        return self.irc.reload_module(whats[1])

    def sub_list_modules(self, connection, event, nick, userhost, what, admin_unlocked):
        """Get the list of loaded modules from DrBotIRC and display it."""

        return ', '.join(self.irc.list_modules())

# vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on;