import os.path
import random

import socket
import urllib.request

from ircfw.plugins.generic_plugin import generic_plugin
import ircfw.constants as const
import ircfw.unparse


class plugin:

    def __init__(
            self,
            plugin_dispatch,
            command_dispatch_backend_replies,
            zmq_ioloop,
            zmq_ctx):
        self.generic_plugin = generic_plugin(
             __name__,
             const.PHOBIAS_PLUGIN,
             [const.PHOBIAS_PLUGIN_NEW_REQUEST],
             plugin_dispatch,
             command_dispatch_backend_replies,
             zmq_ioloop,
             zmq_ctx)
        self.logger = self.generic_plugin.logger

        fh = open(os.path.dirname(__file__) + '/' + 'phobias.txt')
        self.phobias = list(fh)
        fh.close()

    async def main(self):
        while True:
            msg = await self.generic_plugin.read_request()
            self.logger.info('got msg %s', msg)

            topic, zmq_addr, proxy_name, bufsize \
                , senderbytes, paramsbytes, argsbytes = msg

            result = random.choice(self.phobias)

            replies = ircfw.unparse.make_privmsgs(
                senderbytes, paramsbytes, result.encode(
                    'utf8'), int(bufsize.decode('utf8')), 'multiline'
            )

            await self.generic_plugin.send_replies(replies, zmq_addr, proxy_name)
