"""Watch channel topics for changes and note them."""

import logging

from django.utils import timezone

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


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


class TopicMonitor(Plugin):

    """Have IRC commands to do IRC things (join channels, quit, etc.)."""

    def start(self):
        """Set up the handlers."""

        self.connection.reactor.add_global_handler('topic', handle_topic, -20)

        super(TopicMonitor, self).start()

    def stop(self):
        """Tear down handlers."""

        self.connection.reactor.remove_global_handler('topic', handle_topic)

        super(TopicMonitor, self).stop()


def handle_topic(connection, event):
    """Store topic changes in the channel model."""

    channel = event.target
    topic = event.arguments[0]
    setter = event.source
    log.debug("topic change '%s' by %s in %s", topic, setter, channel)

    channel, c = IrcChannel.objects.get_or_create(name=channel)
    channel.topic_msg = topic
    channel.topic_time = timezone.now()
    channel.topic_by = setter
    channel.save()


plugin = TopicMonitor