import time
import datetime
import numpy
import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), "/src/python"))


def iq_buf_collect(dev_a, chcount, npt, dev_b=None, header_id=None, verbose=False):

    if dev_b:
        trace_status = dev_b.reg_read([("trace_status1")])[0]
        print("Status before trace toggle %d" % (trace_status))
        dev_b.reg_write([("trace_ctl")])
        trace_status = dev_b.reg_read([("trace_status1")])[0]
        print("Status after trace toggle %d" % (trace_status))

    # hitting buf_trig is harmless if free-running, essential otherwise
    s = []
    # s should be 1308622870(0x4E000016) (ro_enable = 1, previously filled buffer)
    s.extend(dev_a.reg_read([("trace_status1")]))
    print(s)
    # buf_trig is used to activate a new buffer
#    dev_a.reg_write([("trace_reset_we", 1), ("buf_trig", 0), ("buf_trig", 1), ("buf_trig", 0)])
#    time.sleep(1.0)
    dev_a.reg_write([("trace_reset_we", 1)])
#    time.sleep(1.0)
#    dev_a.reg_write([("buf_trig", 0)])
#    time.sleep(1.0)
#    dev_a.reg_write([("buf_trig", 1)])
#    time.sleep(1.0)
#    dev_a.reg_write([("buf_trig", 0)])
#    time.sleep(1.0)
    s.extend(dev_a.reg_read([("trace_status1")]))
    # now s=[1308622870, 234881046] or [0x4E000016, 0xE000016] when trace_status1=0xE000016, ro_enable=0

    if True:
        print(" ".join(["%8.8x" % x for x in s]))
    retry = 0

    # time to fill the buffer until ro_enable goes high
    while True:
        # trace_status, trace_status2, trace_status2
        # trace_status1 should have ro_enable=0
        # trace_status2 (32 bits), where the first 16 bits is # of filled buffers
        # and last 16 bits includes fault bit, and (if set) the last valid location
        # both trace_status2 reads are same vales
        r = dev_a.reg_read(["trace_status1", "trace_status2", "trace_status2"])
        print(r)
        r = [x + 0x100000000 if x < 0 else x for x in r]
        # print "status %x %x"%(r[0],r[1])
        b_status = r[0]  # trace_status1

        # wait until ro_enable=1, if it's one buffer is full
        if (b_status >> 30) & 1 == 1:
            break
        retry += 1
        time.sleep(0.003)
    # this is just the timestamp, as known to the host computer, not from the FPGA
    datetimestr = datetime.datetime.utcnow().isoformat()+"Z"
    # so the header is the timestamp + trace_status2
    header = datetimestr + " %x" % r[1]
    if header_id:
        header += "\n" + header_id
    if dev_b:
        br = dev_b.reg_read(["trace_status1", "trace_status2"])[0]
    else:
        br = [0]
    if verbose:
        print("%d retries, status %x %x %x" % (retry, r[0], r[1], r[2]))
    if dev_b:
        print("%d  2nd status %x %x" % (br[0], br[1], br[2]))
    # print("")

    # once the buffer is filled, read I and Q buffer from device A and each of len 16384
    # both the buffers have interleaved channel data
    # data structure I = [channel 1 I , channel 2 I, channel 3 I ..... channel 8 I]
    # data structure Q = [channel 1 Q , channel 2 Q, channel 3 Q ..... channel 8 Q]
    dev_a_i = dev_a.reg_read([("trace_i_buf")])[0]
    dev_a_q = dev_a.reg_read([("trace_q_buf")])[0]
    print(dev_a_i)

    if dev_b:
        # Read I and Q buffer from device B, if present
        dev_b_i = dev_b.reg_read([("trace_i_buf")])[0]
        dev_b_q = dev_b.reg_read([("trace_q_buf")])[0]

    if 1:
        for jx in []:  # range(npt/chcount):
            # never envoked
            print(" ".join(["%8.8x" % r[kx] for kx in range(jx*chcount, (jx+1)*chcount)]))
        # build I/Q data based on the number of channels and ends up looking [[I_1], [Q_1], [I_2], [Q_2], ...]
        block = sum([[dev_a_i[ix::chcount], dev_a_q[ix::chcount]] for ix in range(chcount)], [])
        # take the transpose and divide by 2**10 (i.e. 2**(32-trace_rw_fix), where 32 is the data-width, but the actual data is of 22-bits MSB)
        # but the data looks = [I_1, Q_1, I_2, Q_2 ......]
        # when you use nblock, take a transpose to get the columns of I, Q
        nblock = numpy.array(block).transpose()/1024
        if dev_b:
            bblock = sum([[dev_b_i[ix::chcount], dev_b_q[ix::chcount]] for ix in range(chcount)], [])
            bnblock = numpy.array(bblock).transpose()/1024
            nblock = numpy.hstack((nblock, bnblock))
    return (nblock, header)


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


if __name__ == "__main__":

    from argparse import ArgumentParser

    parser = ArgumentParser(description="Board support - Direct ADC I/Q buffer readout")

    parser.add_argument('-a', '--address', dest="address", default=None,
                        help='Device A URL (leep://<IP> or ca://<PREFIX>)')
    parser.add_argument('-b', '--baddress', dest="baddress", default=None,
                        help='Device B URL (leep://<IP> or ca://<PREFIX>)')
    parser.add_argument('-C', '--chcount', dest="chcount", default=2, type=int,
                        help='Number of channels set on channel mask')
    parser.add_argument('-c', '--count', dest="count", default=1, type=int,
                        help='Number I/Q buffer acquisitions')
    parser.add_argument('-i', '--id', dest="header_id", default=None,
                        help='Header ID')
    parser.add_argument('-v', '--verbose', action="store_true", default=False,
                        help='Verbose mode')

    args = parser.parse_args()

    import leep

    # Open communication channel with Device A
    dev_a = leep.open(args.address)

    # If there is a second device, open its communication channel (B)
    if args.baddress:
        dev_b = leep.open(args.baddress)
    else:
        dev_b = None

    dev_a_trace_status = dev_a.reg_read([("trace_status1")])[0]
    # assign trace_status1 = {1'b0, ro_enable, trace_aw_fix, 18'b0, trace_rw_fix};
    # where the bit widths are
    #   1  1'b0
    #   1  ro_enable
    #   6  trace_aw_fix (value = 14)
    #  18  18'b0
    #   6  trace_rw_fix (value = 22)
    #  32   total
    # trace_status1 is always 1308622870 (0x4E000016) when buffer is filled.
    npt = 1 << ((dev_a_trace_status >> 24) & 0x3F)
    # so npt is always 2**14 = 16384, i.e 2**trace_aw_fix, unless you change the firmware

    print("Direct ADC I/Q buffer readout")

    if npt == 1:
        print("Aborting since hardware module not present")
        sys.exit(2)

    print("Acquiring %d points per acquisition" % (npt))

    for run_n in range(args.count):
        # count is the number of blocks of 16k points you want to collect.
        (nblock, header) = iq_buf_collect(dev_a, args.chcount, npt, dev_b=dev_b,
                                          header_id=args.header_id, verbose=args.verbose)
        numpy.savetxt('/data/cpu-b15-rf01/dc_iq_%3.3d' % run_n, nblock, fmt="%d", header=header)

    print("Done")
