# coding: utf-8

import logging

from ircbot.lib import Plugin
from pi.models import PiLog


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


class Pi(Plugin):

    """Use the Monte Carlo method to simulate pi."""

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

        self.connection.reactor.add_global_regex_handler(['pubmsg', 'privmsg'], r'^!pi$',
                                                         self.handle_pi, -20)

        super(Pi, self).start()

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

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

        super(Pi, self).stop()

    def handle_pi(self, connection, event, match):
        """Handle the pi command by generating another value and presenting it."""

        newest, x, y, hit = PiLog.objects.simulate()
        msg = ("({0:.10f}, {1:.10f}) is {2}within the unit circle. π is {5:.10f}. (i:{3:d} p:{4:d})"
               "".format(x, y, "" if hit else "not ", newest.count_inside, newest.count_total, newest.value()))

        return self.bot.reply(event, msg)


plugin = Pi