#!/usr/bin/env python3
# vim: fdm=indent ts=4

import h5py
from itertools import combinations, zip_longest
import matplotlib.pyplot as plt
import numpy as np

import aa_generate_beacon as beacon
import lib


if __name__ == "__main__":
    from os import path
    import sys

    fname = "ZH_airshower/mysim.sry"

    show_plots = True
    ref_ant_id = None # leave None for all baselines

    ####
    fname_dir = path.dirname(fname)
    antennas_fname = path.join(fname_dir, beacon.antennas_fname)
    time_diffs_fname = antennas_fname

    basenames, time_diffs, f_beacon, true_phase_diffs, k_periods = beacon.read_baseline_time_diffs_hdf5(time_diffs_fname)

    f_beacon, tx, antennas = beacon.read_beacon_hdf5(antennas_fname)

    antenna_time_shifts = { a.name: a.attrs['clock_offset'] for a in antennas }


    my_time_shifts = []
    for i,b in enumerate(basenames):
        actual_time_shift = antenna_time_shifts[b[0]] - antenna_time_shifts[b[1]]
        my_time_shifts.append(actual_time_shift)

        print(
                f'B({b[0]}, {b[1]}):',
                time_diffs[i],
                k_periods[i],
                'A', actual_time_shift
            )

    # Make a plot
    N = len(basenames)
    fig, ax = plt.subplots()
    ax.set_xlabel("Baseline combo")
    ax.set_ylabel("[ns]")
    ax.plot(np.arange(N), my_time_shifts, marker='+', label='actual time shifts')
    ax.plot(np.arange(N), time_diffs, marker='x', label='calculated')

    ax.legend()

    plt.show()