import weechat as w
import re, urllib, urllib2, json
weechat = w

SCRIPT_NAME    = "shorten"
SCRIPT_AUTHOR  = "Liam Stanley <me@liamstanley.io>"
SCRIPT_VERSION = "0.2"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC    = "Convert/Shorten all links to http://links.ml/ links"

# script options
settings = {
}


if w.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
                    SCRIPT_DESC, "", ""):
    for option, default_value in settings.iteritems():
        if w.config_get_plugin(option) == "":
            w.config_set_plugin(option, default_value)

    # Hooks we want to hook
    hook_command_run = {
        "input" : ("/input return",  "command_run_input"),
    }
    # Hook all hooks !
    for hook, value in hook_command_run.iteritems():
        w.hook_command_run(value[0], value[1], "")


def post(query):
    data = urllib.urlencode(query)
    u = urllib.urlopen('http://links.ml/add', data)
    bytes = u.read()
    u.close()
    return bytes


def command_run_input(data, buffer, command):
    """Function called when a command "/input xxxx" is run"""
    if command == "/input return": # As in enter was pressed.

        # Get input contents
        user_input = w.buffer_get_string(buffer, 'input')
        if user_input.startswith('/') and not user_input.startswith('//') and not user_input.startswith('/me'):
            return w.WEECHAT_RC_OK
        # Transform it
        urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', user_input)
        if not urls:
            return w.WEECHAT_RC_OK
        for url in urls:
            try:
                data = json.loads(post({'url': url}))
                if not data['success']:
                    w.prnt('', 'Failed to convert %s!' % url)
                    continue
                user_input = user_input.replace(url, str(data['url']))
            except:
                w.prnt('', 'Failed to convert %s!' % url)
                continue
        w.buffer_set(buffer, 'input', user_input)
    return w.WEECHAT_RC_OK
