

class MidiState(object):
    """Various data to keep track what midi in looks like currently"""
    def __init__(self):
        self.midiInIsActive = False
        self.ccState = {}
        for cc in range(0,127):
            self.ccState[cc] = None #start with undefined.
        self.firstActiveNote = None #for chord entry.
        self.cboxMidiPortUid = None #the INPUT midi in port. set in startMidiModule
        self.currentOutputMidiPortUid = None #set in self.setMidiThrough. This changes with the active track
        self.scene = cbox.Document.get_engine().new_scene()
        self.scene.clear() 

    def toggleMidiIn(self):
        self.midiInIsActive = not self.midiInIsActive
        if self.midiInIsActive:
            #CachedTrackDuration is a dict and never cleared completely. So our midiIn will never get touched
            #We hope that nobody uses the PortUid as a track name by chance :)
            api.session.data.cachedTrackDurations[self.cboxMidiPortUid] = api.DINF            
        else:
            api.session.data.cachedTrackDurations[self.cboxMidiPortUid] = 0

            finalizeRecordingBuffer()
        api.callbacksDatabase._prevailingBaseDurationChanged(api.session.data.cursor.prevailingBaseDuration)

    def updateCCState(self, ccNumber, ccValue):
        assert 0 <= ccValue <= 127
        self.ccState[ccNumber] = ccValue

    def setMidiThrough(self, cursorExport):
        """
        Instruct the RT part to echo midi in directly to the connect output ports so we hear the current track with the tracks instrument.
        Added to the cursorChanged api callback"""
        if not self.currentOutputMidiPortUid == cursorExport["cboxMidiOutUuid"]: #most of the time this stays the same e.g. cursor left/right. we only care about up and down
            self.currentOutputMidiPortUid = cursorExport["cboxMidiOutUuid"]
            cbox.JackIO.route_midi_input(midiState.cboxMidiPortUid, cursorExport["cboxMidiOutUuid"])

def startMidiModule(pApi):    
    global api
    api = pApi
    
    #global midiState    
    #midiState = MidiState()
    
    midiState.cboxMidiPortUid = cbox.JackIO.create_midi_input("in")
    cbox.JackIO.set_appsink_for_midi_input(midiState.cboxMidiPortUid, True) #This sounds like a program wide sink, but it is needed for every port.
    cbox.JackIO.route_midi_input(midiState.cboxMidiPortUid, midiState.scene.uuid)
    #midiState.currentOutputMidiPortUid = api.session.data.cursorExport()["cboxMidiOutUuid"] #TODO. Im cursor habn ich das deaktiviert.
    #api.callbacks.setCursor.append(midiState.setMidiThrough) #TODO. Das brauchen wir damit wir das verknüpfte instrument vom track hören.
    return processMidiIn    
