import os,json,pickle,csv
from shutil import copyfile

def event_times( eventTimeFn ):

    eventL = []
    velL   = []
    with open(eventTimeFn,"r") as f:

        rdr = csv.reader(f)

        for row in rdr:
            if row[0] == 'start':
                beginMs = int(row[1])
            elif row[0] == 'key_down':
                key_downMs = int(row[1]) - beginMs
                vel        = int(row[3])
            elif row[0] == 'key_up':
                key_upMs = row[1]

                eventL.append( [ key_downMs, key_downMs+1000 ] )
                velL.append( vel )

    return eventL,velL

def pulse_lengths( pulseLenFn, velL ):

    with open(pulseLenFn,'rb') as f:
        d = pickle.load(f)
        msL = d['msL']
        # note: first posn in table is a multiplier
        msL = [ msL[i]*msL[0] for i in  range(1,len(msL))]
        usL = [ msL[vel-1] for vel in velL ]

    return usL

def convert( inDir, outDir ):

    if not os.path.isdir(outDir):
        os.mkdir(outDir)

    for dirStr in os.listdir(inDir):

        idir = os.path.join( inDir, dirStr )
        
        if os.path.isdir(idir):

            id = 0
            while True:

                eventTimeFn = os.path.join( idir, "labels_%i.csv" % (id) )

                if not os.path.isfile( eventTimeFn ):
                    break
                
                eventTimeL,velL = event_times(eventTimeFn)

                pulseTimeFn = os.path.join( idir, "table_%i.pickle" % (id))

                pulseUsL = pulse_lengths( pulseTimeFn, velL )

                pitch = idir.split("/")[-1]

                if not pitch.isdigit():
                    break

                d = {
                    "pulseUsL":pulseUsL,
                    "pitchL":[ pitch ],
                    "noteDurMs":1000,
                    "pauseDurMs":0,
                    "holdDutyPct":50,
                    "eventTimeL":eventTimeL,
                    "beginMs":0
                }

                odir = os.path.join( outDir, pitch )
                if not os.path.isdir(odir):
                    os.mkdir(odir)

                odir = os.path.join( odir, "%i" % (id) )
                if not os.path.isdir(odir):
                    os.mkdir(odir)

                with open(os.path.join( odir, "seq.json" ),"w") as f:
                    f.write(json.dumps( d ))

                copyfile( os.path.join(idir,"audio_%i.wav" % (id)), os.path.join(odir,"audio.wav"))

                id += 1
                

if __name__ == "__main__":
    inDir = "/home/kevin/temp/picadae_ac_2/full_map"
    outDir = "/home/kevin/temp/p_ac_3_cvt/full_map"

    #inDir = "/home/kevin/temp/picadae_ac_2/week_0"
    #outDir = "/home/kevin/temp/p_ac_3_cvt/week_0"

    convert( inDir, outDir )
    
