import liblo, sys

class Client:
    def __init__(self, host = '127.0.0.1', port = 1234):
        try:
            self.target = liblo.Address(host, port)
        except:
            print >>sys.stderr, 'OSC: Could not connect to server %s:%p' % (host, port)

    def send(self, message):
        try:
            liblo.send(self.target, str(message))
        except:
            print >>sys.stderr, 'OSC: failed to send message [%s]' % str(message)

    def send_action(self, action):
        self.send('ACTION: %s' % action.text)

    def send_words(self, start, words):
        self.send('WORDS(%d): %s' % (start, words))

class Server:
    def __init__(self, host = '127.0.0.1', port = 1234):
        print 'OSC: Creating server at %s:%d' % (host, port)
        self.server = liblo.Server(port)
        self.server.add_method(None, None, self.callback)

    def callback(self, message):
        print 'OSC: Received [%s]' % message

    def run(self):
        print 'OSC: Waiting for messages'
        while True:
            self.server.recv(100)

client = None
def setup(host, port):
    global client
    client = Client(host, port)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        client = Client()
        client.send(' '.join(sys.argv[1:]))
    else:
        server = Server()
        server.run()