#!/usr/bin/env python
# Ingen Interactive Shell
# Copyright 2011-2015 David Robillard <http://drobilla.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import ingen
import os.path
import re
import shlex
import sys
import time
try:
    import readline
except:
    pass

# Python 2 compatibility
try:
    input = raw_input
except NameError:
    pass

def print_usage():
    print('''Usage: ingenish [OPTION]... [COMMAND [ARGUMENT]...]

A command line interface to an Ingen server.  A command can be given directly
on the command line, or when run with no arguments an interactive shell is
launched.

Options:
    -s ADDRESS    The address of the Ingen server.  Default is the local server
                  at unix:///tmp/ingen.sock but remote servers can be used with
                  an address like tcp:///my-ingen-server-host:16180

Commands:
    put SUBJECT BODY
    set SUBJECT KEY VALUE
    connect TAIL HEAD
    disconnect TAIL HEAD
    patch SUBJECT REMOVE ADD
    delete SUBJECT
    help
    exit

Subjects are specified by URI, relative to the engine.  The top level audio
graph has the path /graph, so for example, a port on a block might have the
(relative) URI /graph/osc/freq.

Bodies are specified in fragments of Turtle, just as written in Ingen graph files.

Example:
    put /graph/left_in 'a lv2:InputPort ; a lv2:AudioPort'
    put /graph/left_out 'a lv2:OutputPort ; a lv2:AudioPort'
    put /graph/tone 'a ingen:Block ; lv2:prototype <http://drobilla.net/plugins/mda/Shepard>'
    put /graph/combo 'a ingen:Block ; lv2:prototype <http://drobilla.net/plugins/mda/Combo>'
    connect /graph/left_in /graph/tone/left_in
    connect /graph/tone/left_out /graph/combo/left_in
    connect /graph/combo/left_out /graph/left_out
    set /graph/tone/output ingen:value 0.7
''')

def run(cmd):
    if cmd[0] == 'help':
        print_usage()
    elif cmd[0] == 'exit':
        sys.exit(0)
    elif cmd[0] == 'get' and len(cmd) == 2:
        print(ingen.get(cmd[1]).serialize(format='n3'))
    elif cmd[0] == 'put' and len(cmd) == 3:
        return ingen.put(cmd[1], cmd[2])
    elif cmd[0] == 'patch' and len(cmd) == 4:
        return ingen.patch(cmd[1], cmd[2], cmd[3])
    elif cmd[0] == 'set' and len(cmd) == 4:
        return ingen.set(cmd[1], cmd[2], cmd[3])
    elif cmd[0] == 'connect' and len(cmd) == 3:
        return ingen.connect(cmd[1], cmd[2])
    elif cmd[0] == 'disconnect' and len(cmd) == 3:
        return ingen.disconnect(cmd[1], cmd[2])
    elif cmd[0] == 'delete' and len(cmd) == 2:
        return ingen.delete(cmd[1])
    return False

a = 1
server = 'unix:///tmp/ingen.sock'
if len(sys.argv) > 1:
    if sys.argv[a] == '-s':
        server = sys.argv[a + 1]
        a = a + 2
    elif sys.argv[a][0] == '-':
        print_usage()
        sys.exit(1)

ingen = ingen.Remote(server)

if len(sys.argv) - a == 0:
    print('Ingen server at %s' % server)
    while True:
        try:
            run(shlex.split(input('> ')))
        except (EOFError, KeyboardInterrupt, SystemExit):
            break
        except:
            print('error: %s' % sys.exc_info()[1])
else:
    try:
        update = run(sys.argv[a:])
        if update:
            print(update.serialize(format='n3'))
    except:
        print('error: %s' % sys.exc_info()[1])