#!/usr/bin/env python

name_base = 'org.jackaudio'
control_interface_name = name_base + '.JackControl'
configure_interface_name = name_base + '.JackConfigure'
service_name = name_base + '.service'

import sys
import os
from traceback import print_exc

import dbus

def bool_convert(str_value):
    if str_value.lower() == "false":
        return False

    if str_value.lower() == "off":
        return False

    if str_value.lower() == "no":
        return False

    if str_value == "0":
        return False

    if str_value.lower() == "(null)":
        return False

    return bool(str_value)

def dbus_type_to_python_type(dbus_value):
    if type(dbus_value) == dbus.Boolean:
        return bool(dbus_value)
    if type(dbus_value) == dbus.Int32 or type(dbus_value) == dbus.UInt32:
        return int(dbus_value)
    return dbus_value

def python_type_to_jackdbus_type(value, type_char):
    type_char = str(type_char)

    if type_char == "b":
        return bool_convert(value);
    elif type_char == "y":
        return dbus.Byte(value);
    elif type_char == "i":
        return dbus.Int32(value)
    elif type_char == "u":
        return dbus.UInt32(value)

    return value

def dbus_type_to_type_string(dbus_value):
    if type(dbus_value) == dbus.Boolean:
        return "bool"
    if type(dbus_value) == dbus.Int32:
        return "sint"
    if type(dbus_value) == dbus.UInt32:
        return "uint"
    if type(dbus_value) == dbus.Byte:
        return "char"
    if type(dbus_value) == dbus.String:
        return "str"

    return None                         # throw exception here?

def dbus_typesig_to_type_string(type_char):
    type_char = str(type_char)
    if type_char == 'i':
        return "sint"
    if type_char == 'u':
        return "uint"
    if type_char == 'y':
        return "char"
    if type_char == 's':
        return "str"
    if type_char == 'b':
        return "bool"

    print 'shit'
    return None                         # throw exception here?

def main():
    if len(sys.argv) == 1:
        print "Usage: %s [command] [command] ..." % os.path.basename(sys.argv[0])
        print "Commands:"
        print "    exit                       - exit jack dbus service (stops jack server if currently running)"
        print "    status                     - check whether jack server is started, return value is 0 if runing and 1 otherwise"
        print "    start                      - start jack server if not currently started"
        print "    stop                       - stop jack server if currenly started"
        print "    dl                         - get list of available drivers"
        print "    dg                         - get currently selected driver"
        print "    ds <driver>                - select driver"
        print "    dp                         - get parameters of currently selected driver"
        print "    dpd <param>                - get long description for driver parameter"
        print "    dps <param> <value>        - set driver parameter"
        print "    il                         - get list of available internals"
        print "    ip <name>                  - get parameters of given internal"
        print "    ipd <name> <param>         - get long description for internal parameter"
        print "    ips <name> <param> <value> - set internal parameter"
        print "    iload <name>               - load internal"
        print "    iunload <name>             - unload internal"
        print "    ep                         - get engine parameters"
        print "    epd <param>                - get long description for engine parameter"
        print "    eps <param> <value>        - set engine parameter"
        sys.exit(0)
    
    bus = dbus.SessionBus()

    controller = bus.get_object(service_name, "/org/jackaudio/Controller")
    control_iface = dbus.Interface(controller, control_interface_name)
    configure_iface = dbus.Interface(controller, configure_interface_name)

    # check arguments
    index = 1
    while index < len(sys.argv):
        arg = sys.argv[index]
        index += 1
        try:
            if arg == "exit":
                print "--- exit"
                control_iface.Exit()
            elif arg == "status":
                print "--- status"
                if control_iface.IsStarted():
                    print "started"
                    sys.exit(0)
                else:
                    print "stopped"
                    sys.exit(1)
            elif arg == 'start':
                print "--- start"
                control_iface.StartServer()
            elif arg == 'stop':
                print "--- stop"
                control_iface.StopServer()
            elif arg == 'ism':
                if control_iface.IsManuallyActivated():
                    print "Manually activated"
                else:
                    print "Automatically activated"
            elif arg == 'dl':
                print "--- drivers list"
                drivers = configure_iface.GetAvailableDrivers()
                for driver in drivers:
                    print driver
            elif arg == 'dg':
                print "--- get selected driver"
                driver = configure_iface.GetSelectedDriver()
                if not driver:
                    print "no driver selected"
                else:
                    print driver
            elif arg == 'ds':
                if index >= len(sys.argv):
                    print "driver select command requires driver name argument"
                    sys.exit()

                arg = sys.argv[index]
                index += 1

                print "--- driver select \"%s\"" % arg
                configure_iface.SelectDriver(arg)
            elif arg == 'dp':
                print "--- get driver parameters (type:isset:default:value)"

                params = configure_iface.GetDriverParametersInfo()
                
                #print params
                for param in params:
                    typestr = dbus_typesig_to_type_string(param[0])
                    name = param[1]
                    #print name
                    descr = param[2]
                    #print descr
                    isset, default, value = configure_iface.GetDriverParameterValue(name)
                    #print typestr
                    if bool(isset):
                        isset = "set"
                    else:
                        isset = "notset"
                    value = dbus_type_to_python_type(value)
                    default = dbus_type_to_python_type(default)

                    print "%20s: %s (%s:%s:%s:%s)" %(name, descr, typestr, isset, default, value)
            elif arg == 'dpd':
                if index >= len(sys.argv):
                    print "get driver parameter long description command requires parameter name argument"
                    sys.exit()

                param = sys.argv[index]
                index += 1

                print "--- get driver parameter description (%s)" % param
                type_char, name, short_descr, long_descr = configure_iface.GetDriverParameterInfo(param)
                print long_descr,
            elif arg == 'dps':
                if index + 1 >= len(sys.argv):
                    print "driver parameter set command requires parameter name and value arguments"
                    sys.exit()

                param = sys.argv[index]
                index += 1
                value = sys.argv[index]
                index += 1

                print "--- driver param set \"%s\" -> \"%s\"" % (param, value)

                type_char, name, short_descr, long_descr = configure_iface.GetDriverParameterInfo(param)
                configure_iface.SetDriverParameterValue(param, python_type_to_jackdbus_type(value, type_char))
            elif arg == 'ep':
                print "--- get engine parameters (type:isset:default:value)"

                params = configure_iface.GetEngineParametersInfo()
                
                #print params
                for param in params:
                    typestr = dbus_typesig_to_type_string(param[0])
                    name = param[1]
                    #print name
                    descr = param[2]
                    #print descr
                    isset, default, value = configure_iface.GetEngineParameterValue(name)
                    #print typestr
                    if bool(isset):
                        isset = "set"
                    else:
                        isset = "notset"
                    value = dbus_type_to_python_type(value)
                    default = dbus_type_to_python_type(default)

                    print "%20s: %s (%s:%s:%s:%s)" %(name, descr, typestr, isset, default, value)
            elif arg == 'epd':
                if index >= len(sys.argv):
                    print "get engine parameter long description command requires parameter name argument"
                    sys.exit()

                param_name = sys.argv[index]
                index += 1

                print "--- get engine parameter description (%s)" % param_name

                type_char, name, short_descr, long_descr = configure_iface.GetEngineParameterInfo(param_name)
                print long_descr,
            elif arg == 'eps':
                if index + 1 >= len(sys.argv):
                    print "engine parameter set command requires parameter name and value arguments"
                    sys.exit()

                param = sys.argv[index]
                index += 1
                value = sys.argv[index]
                index += 1

                print "--- engine param set \"%s\" -> \"%s\"" % (param, value)

                type_char, name, short_descr, long_descr = configure_iface.GetEngineParameterInfo(param)
                configure_iface.SetEngineParameterValue(param, python_type_to_jackdbus_type(value, type_char))
            elif arg == 'il':
                print "--- internals list"
                internals = configure_iface.GetAvailableInternals()
                for internal in internals:
                    print internal
            elif arg == 'ip':
                print "--- get internal parameters (type:isset:default:value)"

 		if index >= len(sys.argv):
                    print "internal parameters command requires internal name argument"
                    sys.exit()

                internal_name = sys.argv[index]
                index += 1
                params = configure_iface.GetInternalParametersInfo(internal_name)
                
                #print params
                for param in params:
                    typestr = dbus_typesig_to_type_string(param[0])
                    name = param[1]
                    #print name
                    descr = param[2]
                    #print descr
                    isset, default, value = configure_iface.GetInternalParameterValue(internal_name, name)
                    #print typestr
                    if bool(isset):
                        isset = "set"
                    else:
                        isset = "notset"
                    value = dbus_type_to_python_type(value)
                    default = dbus_type_to_python_type(default)

                    print "%20s: %s (%s:%s:%s:%s)" %(name, descr, typestr, isset, default, value)
            elif arg == 'ipd':
	        if index + 1 >= len(sys.argv):
                    print "get internal parameter long description command requires internal and parameter name arguments"
                    sys.exit()

                name = sys.argv[index]
                index += 1
                param = sys.argv[index]
                index += 1

                print "--- get internal parameter description (%s)" % param
                type_char, name, short_descr, long_descr = configure_iface.GetInternalParameterInfo(name, param)
                print long_descr
 	    elif arg == 'ips':
	        if index + 2 >= len(sys.argv):
                    print "get internal parameter long description command requires internal, parameter name and value arguments"
                    sys.exit()

                internal_name = sys.argv[index]
                index += 1
                param = sys.argv[index]
                index += 1
		value = sys.argv[index]
                index += 1
		
		print "--- internal param set \"%s\" -> \"%s\"" % (param, value)

                type_char, name, short_descr, long_descr = configure_iface.GetInternalParameterInfo(internal_name, param)
                configure_iface.SetInternalParameterValue(internal_name, param, python_type_to_jackdbus_type(value, type_char))
            elif arg == 'iload':
                print "--- load internal"

 		if index >= len(sys.argv):
                    print "load internal command requires internal name argument"
                    sys.exit()

                name = sys.argv[index]
                index += 1
                result = control_iface.LoadInternal(name)
            elif arg == 'iunload':
                print "--- unload internal"

 		if index >= len(sys.argv):
                    print "unload internal command requires internal name argument"
                    sys.exit()

                name = sys.argv[index]
                index += 1
                result = control_iface.UnloadInternal(name)
            else:
                print "Unknown command '%s'" % arg
        except dbus.DBusException, e:
            print "DBus exception: %s" % str(e)

if __name__ == '__main__':
    main()
