import logging

from ircbot.lib import Plugin

from weather.lib import get_conditions_for_query, get_forecast_for_query


log = logging.getLogger('weather.ircplugin')


class Weather(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'^!weather\s+(.*)$',
                                                         self.handle_weather, -20)

        super(Weather, self).start()

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

        self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_weather)

        super(Weather, self).stop()

    def handle_weather(self, connection, event, match):
        """Handle IRC input for a weather queries."""

        # see if there was a specific command given in the query, first
        query = match.group(1)
        queryitems = query.split(" ")
        if len(queryitems) <= 0:
            return

        # search for commands
        if queryitems[0] == 'conditions':
            # current weather query
            results = get_conditions_for_query(queryitems[1:])
            return self.bot.reply(event, results)
        elif queryitems[0] == 'forecast':
            # forecast query
            results = get_forecast_for_query(queryitems[1:])
            return self.bot.reply(event, results)
        else:
            # assume they wanted current weather
            results = get_conditions_for_query(queryitems)
            return self.bot.reply(event, results)


plugin = Weather