import sys
import os

import numpy

sys.path.append(os.path.join(os.path.dirname(__file__), "../submodules/FEED/src/python"))
import leep


def sel_waves_run(dev, chcount=8, count=1, header_id=None, zone=0, filewritepath=None):

    slow_abi_ver = dev.regmap["__metadata__"]["slow_abi_ver"]

    for run_n in range(count):
        (nblock, datetimestr, slow_data) = sel_wave_collect(dev, chcount=chcount, zone=zone, verbose=True)
        isd = interpret_slow_data(slow_data, abi_ver=slow_abi_ver)
        header = datetimestr + " %d %d" % (isd[0], isd[5])  # circle_count and time_stamp
        if header_id:
            header += "\n" + header_id

        if filewritepath:
            # Make sure path has terminating '/'
            if filewritepath.endswith('/') is False:
                filewritepath = filewritepath + '/'
        else:
            filewritepath = ''

        wname = filewritepath + 'ctl%d_iq_%3.3d' % (zone, run_n)
        numpy.savetxt(wname, numpy.asarray(nblock).T, fmt="%10.7f", header=header)


def interpret_slow_data(slow_data, abi_ver=0):
    # circle_count, circle_stat, adc1_min, adc1_max, adc2_min, adc2_max, adc3_min, adc3_max, tag_now, tag_old, timestamp
    # if abi_ver >= 1, dsp_status is inserted after tag_old
    circle_count = slow_data[0]*256+slow_data[1]
    circle_stat = slow_data[2]*256+slow_data[3]
    tag_now = slow_data[16]
    tag_old = slow_data[17]
    # Three channels of ADC min/max
    mm = [slow_data[ix]*256+slow_data[ix+1] for ix in range(4, 16, 2)]
    mm = [m-65536 if m > 32767 else m for m in mm]
    # (almost) 64-bit timestamp
    time_stamp = 0
    ts_base = 25 if abi_ver < 1 else 27
    for ix in range(8):
        time_stamp = time_stamp*256 + slow_data[ts_base-ix]
    time_stamp = time_stamp/32
    if abi_ver >= 1:
        dsp_status = slow_data[18]*256+slow_data[19]
        # print("dsp_status %x" % dsp_status)
    else:
        dsp_status = 0  # not sure this is the best choice
    return circle_count, circle_stat, mm, tag_now, tag_old, time_stamp, dsp_status


def sel_wave_collect(dev, chcount=8, zone=1, verbose=False):

    # Firmware conveyor belt dependent
    # Translate channel count to list of channels
    chans = list(range(2, 2+chcount))
    dev.set_channel_mask(chans=chans, instance=[zone])

    # Collect I/Q waveforms
    tag_match, slow_data, time_now = dev.wait_for_acq(instance=[zone])
    datetimestr = time_now.isoformat()+"Z"
    channels = dev.get_channels(chans=chans, instance=[zone])

    # First 17 bytes of slow_data are padding
    return (channels, datetimestr, slow_data[17:45])


def usage():
    print('python sel_waves.py -a 192.168.21.12 -c 1')


if __name__ == "__main__":

    from argparse import ArgumentParser

    parser = ArgumentParser(description="RFS/PRC doble-buffered I/Q waveform acquisition")

    parser.add_argument('-a', '--address', dest="dev_addr", default=None,
                        help='Device URL (leep://<IP> or ca://<PREFIX>)')
    parser.add_argument('-C', '--chcount', dest='chcount', default=8, type=int,
                        help='Number of channels to acquire')
    parser.add_argument('-c', '--count', dest='count', default=1, type=int,
                        help='Number of waveform acquisitions')
    parser.add_argument('-z', '--zone', dest='zone', default=1, type=int, choices=[0, 1],
                        help='Cavity controller (zone)')
    parser.add_argument('-w', '--filewritepath', dest='filewritepath', default=None,
                        help='Output file path')
    parser.add_argument('-i', '--header_id', dest='header_id', default=None,
                        help='Header ID')

    args = parser.parse_args()

    print('SEL waves')
    print('Carrier board URL %s' % args.dev_addr)
    dev = leep.open(args.dev_addr, instance=[])

    sel_waves_run(dev, chcount=args.chcount, count=args.count,
                  header_id=args.header_id, zone=args.zone, filewritepath=args.filewritepath)
