#!/usr/bin/env python
#!/usr/local/bin/python3

import struct
import sys
import json
import webbrowser
import glob

def send_result(result, url):
    send_message('{"result": "%s", "url": "%s" }' % (result, url))

def send_message(message):
    sys.stdout.write(struct.pack('I', len(message)))
    sys.stdout.write(message)
    sys.stdout.flush()

def receive_message():
    
    text_length_bytes = sys.stdin.read(4)

    if len(text_length_bytes) == 0:
        return False
    
    text_length = struct.unpack('i', text_length_bytes)[0]
    
    return json.loads(sys.stdin.read(text_length).decode('utf-8'))

while True:
    message = receive_message()
    
    if not message:
        break

    if 'options' in message:
        try:
            f = open('data.json',)
            data = f.read()
            send_message('{"options": %s}' % (data))
        except IOError:
            send_message('{"options": {}}')
        finally:
            f.close()s
            
    if 'test' in message:
        try:
            send_message('{"test": {}}')
        except IOError:
            send_message('{"test": {}}')

    if 'url' in message:
        try:
            webbrowser.open(message['url'])
        except:
            send_result("error", message['url'])
        else:
            send_result("success", message['url'])
    
exit(0)
