#!/usr/bin/python
# \file hpisave.py
#
# Example use of python hpi bindings
#

import sys,time

def MuxDetails(h):
    e,cnode,cindex=hpi.Multiplexer_GetSource(h)
    print 'hpi.Multiplexer_SetSource(ch, hpi.%s, %d)' % (hpi.SourceDict[cnode], cindex)

def TunerDetails(h):
    e,cband=hpi.Tuner_GetBand(h);
    print 'hpi.Tuner_SetBand(ch, hpi.%s)' % hpi.TunerBandDict[cband]
    e,cfreq=hpi.Tuner_GetFrequency(h);
    print 'hpi.Tuner_SetFrequency(ch,',cfreq,')'

def SampleClockDetails(h):
    e,cauto = hpi.SampleClock_GetAuto(h)
    if not e:
        print 'hpi.SampleClock_SetAuto(ch,',cauto,')'

    e,crate=hpi.SampleClock_GetLocalRate(h)
    if not e:
        print 'hpi.SampleClock_SetLocalRate(ch,',crate,')'

    e,csource=hpi.SampleClock_GetSource(h)
    if not e:
        try:
            print 'hpi.SampleClock_SetSource(ch, hpi.%s)' % hpi.SampleClockSourceDict[csource]
        except:
            print '# Unknown source', csource

    e,csource=hpi.SampleClock_GetSourceIndex(h)
    if not e:
        print 'hpi.SampleClock_SetSourceIndex(ch,',csource,')'

def VolumeDetails(h):
    e, gain=hpi.Volume_GetGain(h);
    print 'hpi.Volume_SetGain(ch,',gain,')'

def LevelDetails(h):
    e,gain=hpi.Level_GetGain(h);
    print 'hpi.Level_SetGain(ch,',gain,')'

def UniversalDetails(h):
    #e = get value
    e, ent = hpi.Object_GetInfoEntity(h)
    if e: return
    e, t, items,role, value = hpi.Entity_Unpack(ent)
    if e: return

    if role == hpi.entity_role_block:
        print '# Block'
    elif role == hpi.entity_role_parameter_port:
        print '# parameter'
        e, ent = hpi.Object_GetValueEntity(h)
        if e: return
        e, type, items,role, vptr = hpi.Entity_Unpack(ent)
        e, value = hpi.Object_GetValue(h, type, items)
        if type == hpi.entity_type_cstring:
            print 'hpi.Object_SetValue(ch, hpi.%s, """%s""")' % (hpi.EntityTypeDict[type], value)
        elif type == hpi.entity_type_bit and items < 2:
            print 'hpi.Object_SetValue(ch, hpi.%s, "%s")' % (hpi.EntityTypeDict[type], value)
        else:
            print 'hpi.Object_SetValue(ch, hpi.%s, %s)' % (hpi.EntityTypeDict[type], value)
    else:
        print '# Dont know what to do with role %s' % hpi.EntityRoleDict[role]


def cleanup():
    """Close HPI mixer, adapter and subsystem."""
    hpi.Mixer_Close(hx)
    hpi.Adapter_Close(adapter)
    hpi.SubSys_Free()


def SaveControls(hx):
    e=0
    ci=0
    while (e == 0):
        e,srctype,srcindex,desttype,destindex,ctrltype,ch=hpi.Mixer_GetControlByIndex(hx,ci)

        if (e): break
        try:
            if (CtrlSave.has_key(ctrltype)):
                ss = 'hpi.' + hpi.SourceDict[srctype]
                ds = 'hpi.' + hpi.DestDict[desttype]
                cs = 'hpi.' + hpi.ControlDict[ctrltype]
                rp = '%s, %s, %s, %s, %s' % (ss, srcindex, ds,destindex, cs)
                print 'e,ch=hpi.Mixer_GetControl(hx, %s)' %  rp
                print "print 'restoring %d: %s'" % (ci, rp)

                CtrlSave[ctrltype](ch)
                print 'time.sleep(0.005)'
        except KeyError:
            pass

        ci += 1


def parseArgs():
    """Parse the commandline arguments"""
    from optparse import OptionParser, OptionGroup

    parser = OptionParser()
    parser.add_option('-a','--adapter',type='int',dest='adapter',
                      help='Adapter index. Default=%default', default=0)

    return parser.parse_args()


############################################################################

if __name__ == '__main__':
    opts, args = parseArgs()

    adapter = opts.adapter

    import audioscience.hpi as hpi

    hpi.setup(opts.adapter)

    CtrlSave={
    hpi.CONTROL_VOLUME:VolumeDetails,
    hpi.CONTROL_LEVEL:LevelDetails,
    hpi.CONTROL_MULTIPLEXER:MuxDetails,
    hpi.CONTROL_TUNER:TunerDetails,
    hpi.CONTROL_SAMPLECLOCK:SampleClockDetails,
    hpi.CONTROL_UNIVERSAL:UniversalDetails,
    }

    e=hpi.Adapter_Open(adapter)
    if e:
            sys.exit("Error " + repr(e))

    ai=hpi.Adapter_GetInfo(adapter)
    e,hx=hpi.Mixer_Open(adapter)
    if e:
            sys.exit("Mixeropen Error " + repr(e))

    preamble = """#!/usr/bin/env python
import sys
import time
import audioscience.hpi as hpi
adapter=%d
if (len(sys.argv) > 1) :
    adapter = int(sys.argv[1])
hpi.Adapter_Open(adapter)
e,hx=hpi.Mixer_Open(adapter)"""

    print preamble % adapter
    SaveControls(hx)
    print '# end'
