import os,sys,json
import common
import matplotlib.pyplot as plt
import plot_seq_1

def plot_calibrate( cfg, pitch, dataD ):

    dataL = [ (d['pulse_us'], d['hm']['db'], d['targetDb'], d['matchFl'],d['skipMeasFl'],d['annIdx']) for d in dataD['measD'][pitch] ]

    udmL = [(t[0],t[1],t[3]) for t in dataL]
    udmL = sorted( udmL, key=lambda x: x[0] )
    usL,dbL,matchL = zip(*udmL)

    fig,ax = plt.subplots()

    musL = [us for us,db,m in udmL if m]
    mdbL = [db for us,db,m in udmL if m]

    ax.plot(musL,mdbL,marker='o',color='red',linestyle='None')
        
    ax.plot(usL,dbL,marker='.')
    
    initDataDir = os.path.expanduser(dataD['cfg']['inDir'])
    usL,dbL,_,_,_ = plot_seq_1.get_merged_pulse_db_measurements( initDataDir, int(pitch), cfg['analysisD'] )
    

    ax.plot(usL,dbL,marker='.')

    plt.show()

if __name__ == "__main__":

    inDir = sys.argv[1]
    cfgFn = sys.argv[2]
    pitch = sys.argv[3]

    cfg = common.parse_yaml_cfg(cfgFn)
    cfg = cfg.calibrateArgs

    dataFn = os.path.join(inDir,"meas.json")
    with open(dataFn,"r") as f:
        dataD = json.load(f)
        
    print("pitchL:",dataD['cfg']['pitchL'],"targetDbL:",dataD['cfg']['targetDbL'])
    plot_calibrate( cfg, pitch, dataD )
