#!/usr/bin/python3
import plotly.graph_objs as go
from decimal import *
from sys import argv


t_x502_sync_mode = ["INTERNAL", "EXTERNAL_MASTER", "SYN1_RISE", "SYN1_FALL", "none 1", "none 2","SYN2_RISE", "SYN2_FALL", "???"]
t_x502_lch_mode = ["COMM", "DIFF", "ZERO", "???"]
t_x502_adc_range = ["+-10V", "+-5V", "+-2V", "+-1V", "+-0.5V", "+-0.2V", "???"]



ADC_settings = {"sync_frec_source":"???", "sync_start_source": "???", "chans":{}}


def main():
  chart = go.Figure()
  chart.add_trace(go.Scatter(x=[1,2,3], y=[1,2,3]))
  chart.show()


if __name__ == "__main__":
  print("parsing")
  print("=======================")
  if len(argv) == 1:
    main()
  else:
    f = open(argv[1], "rt")
    data = {"markers":{"N":[], "text":[]}}
    values_N = 0
    for line in f:
        #print(line)
      #print(line, len(line))
      len_line = len(line)
      try:
        if (len_line >= 11):
          if (line[:2] == "0x"):
            values_N += 1
            header = line[2:4]
            value = line[4:10]
            if not(header in data):
              print("New msg type!")
              print(line)
              data[header] = []
              data[header + "_N"] = []
              data[header + "_hex"] = []
            value_unsigned = int(value, 16)
            if (value_unsigned > 0x7FFFFF):
              value_signed = (value_unsigned) - 0xFFFFFF
            else:
              value_signed = value_unsigned
            data[header].append(value_signed)
            data[header + "_hex"].append(value)
            data[header + "_N"].append(values_N)
          else:
            line_splt = line.split()
            print(line_splt)
            if line_splt[0] == "sync_frec_source:":
              val = int(line_splt[1])
              ADC_settings["sync_frec_source"] = t_x502_sync_mode[val]
            elif line_splt[0] == "sync_start_source:":
              val = int(line_splt[1])
              ADC_settings["sync_start_source"] = t_x502_sync_mode[val]
            elif line_splt[0] == "chan:":
              chan_N = int(line_splt[1][:-1])
              chan_mode = int(line_splt[3][:-1])
              chan_range = int(line_splt[5])
              ADC_settings["chans"][chan_N] = {"mode":t_x502_lch_mode[chan_mode], "range":t_x502_adc_range[chan_range]}
            elif line_splt[0] == "marker":
              data["markers"]["N"].append(values_N)
              data["markers"]["text"].append(line)

            else:
              print("strange line:")
              print(line)

              
      except ValueError:
        pass
      except IndexError:
        pass
      if (values_N > 10000):
#        break
        pass
    f.close()
    print("data samples:", values_N)
    print(ADC_settings)
    ADC_settings_str = ""
    ADC_settings_str += "sync_frec_source: " + ADC_settings["sync_frec_source"] + "<br>"
    ADC_settings_str += "sync_start_source: " + ADC_settings["sync_start_source"] + "<br>"
    for key, val in ADC_settings["chans"].items():
        ADC_settings_str += "  chan" + str(key) + ": " + str(val)+ "<br>"
    print(ADC_settings_str)
    chart = go.Figure()
    chart.update_layout(title=argv[1] + "<br>" + ADC_settings_str)
    chart.add_trace(go.Scattergl(x=data["markers"]["N"], y=[i for i in range(len(data["markers"]["N"]))], name="markers", mode="markers", text=data["markers"]["text"]))
    for key, val in data.items():
      if key != "markers":
        if (key.count("_N") + key.count("_hex")) == 0:
          #print(key+"_hex :", data[key+"_hex"])
          if (len(data[key]) > 1000):
            chart.add_trace(go.Scattergl(x=data[key+"_N"], y=data[key], name=key, mode="lines", text=data[key+"_hex"]))
          else:
            chart.add_trace(go.Scattergl(x=data[key+"_N"], y=data[key], name=key, mode="markers", text=data[key+"_hex"]))
            #chart.add_trace(go.Scattergl(x=data[key+"_N"], y=data[key], name=key, mode="markers+lines", text=data[key+"_hex"]))

         # chart.add_trace(go.Scattergl(x=data[key+"_N"], y=data[key], name=key, mode="lines+markers", text=data[key+"_hex"]))
#    chart.show()
    chart.write_html(argv[1] + ".html")

