import ctypes
import os.path
import time
import numpy as np
from matplotlib import pyplot as plt

import data_structures

def db20(x):
    return 20*np.log10(np.abs(x))


def db20n(x):
    x = db20(x)
    x = x - np.max(x)
    return x


def main():
    print('Hello')

    clk = 187.5e6

    # Parse Data
    headers = []
    offset = 0

    file = 'test1.bin'
    fid = open(file, 'rb')

    # Find header, recording buffer could have wrapped depending on data rate and how long we ran for
    hdr_sync = False
    while not hdr_sync:
        # data = recorder.buffer[offset:offset + 4]
        data = fid.read(4)
        sync_word = np.frombuffer(data, dtype=np.uint32)[0]
        if sync_word == 0xAABBCCDD:
            hdr_sync = True
            print('Header found at offset', offset)
            fid.seek(-4, 1)

    # Get the first header
    header = fid.read(ctypes.sizeof(data_structures.CpiHeader))
    header = data_structures.CpiHeader.from_buffer_copy(header)
    fid.seek(-ctypes.sizeof(data_structures.CpiHeader), 1)

    # CPI Parameters (timing values are in clk ticks)
    num_pulses = header.num_pulses
    num_samples = header.num_samples
    pri = header.pri
    inter_cpi = header.inter_cpi
    data_size = num_pulses * num_samples * 4

    file_size = os.path.getsize(file)
    expected_num_cpis = int(file_size / (ctypes.sizeof(data_structures.CpiHeader) + data_size))
    print('File Size', file_size)
    print('Expected CPIS:', expected_num_cpis)


    for i in range(expected_num_cpis):
        # Get Header
        data = fid.read(ctypes.sizeof(data_structures.CpiHeader))
        headers.append(data_structures.CpiHeader.from_buffer_copy(data))

        # Get CPI
        data = fid.read(data_size)

    # Check some header fields
    cpi_times = np.array([x.system_time for x in headers]) / 187.5e6
    pps_frac = np.array([x.pps_frac_sec for x in headers]) / 187.5e6
    pps_sec = np.array([x.pps_sec for x in headers])
    utc_time = pps_sec + pps_frac
    print(pri, inter_cpi, num_pulses * pri + inter_cpi)
    print(cpi_times - cpi_times[0])
    print(pps_frac)
    print(pps_sec - pps_sec[0])

    # Plot last CPI
    data2 = np.frombuffer(data, dtype=np.int16)
    i = data2[0::2]
    q = data2[1::2]
    iq = i + 1j * q
    iq = iq.reshape(-1, num_samples)
    iq = iq + 1e-15

    vmin = -60
    vmax = 0

    plt.figure()
    plt.plot(np.diff(cpi_times))
    plt.plot(np.diff(pps_frac))
    # plt.ylim([0, .04])

    # plt.figure()
    # plt.plot(iq.T.real, '.-')
    # plt.plot(iq.T.imag, '--.')
    # plt.grid()
    #
    # plt.figure()
    # plt.imshow(db20n(iq), aspect='auto', interpolation='nearest', vmin=vmin, vmax=vmax)
    # plt.ylabel('Pulse Count')
    # plt.xlabel('Sample Count')
    # plt.colorbar()


    plt.show()


if __name__ == '__main__':

    main()
