import json
import urllib3
from urllib.parse import quote, urlparse

from aqbot.lib.plugins.plugin import PluginObject


__all__ = ["JavascriptPlugin"]


class JavascriptPlugin(PluginObject):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def setup(self):
        self.command_manager.add(self, self.js_cmd, "!js")

    def js_cmd(self, listener, sender, target, args):
        arg_list = args.split()

        if len(arg_list) < 1:
            self.messenger.msg(target, "No code to execute!")

        http = urllib3.PoolManager()
        jsurl = "http://52.3.107.139:3000/%s" % quote(args)
        o = urlparse(jsurl)
        r = http.request('GET', o.geturl())
        if self.is_json(r.data.decode('UTF-8')):
            pd = json.loads(r.data.decode('UTF-8'))
        else:
            pd = r.data.decode('UTF-8')
        self.messenger.msg(target, pd)

    @staticmethod
    def is_json(myjson):
        try:
            json.loads(myjson)
        except ValueError:
            return False
        return True

