"""Live plot of the Z acceleration from the ufp_lsm6 Arduino example.

    python examples/accelerometer.py [PORT]

Each `accel` event carries `first_sample` (index of its first sample) and `xyz`,
20 samples interleaved as [x0, y0, z0, x1, y1, z1, ...] in mg. Samples are stored
in a ring buffer indexed by sample number, so samples that were dropped show up
as gaps instead of shifting the time axis.
"""
import sys
import threading

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

import ufp

WINDOW_S = 3.0   # time span shown
FPS = 60


def main():
    port = sys.argv[1] if len(sys.argv) > 1 else "COM10"

    with ufp.connect(port) as board:
        config = board.get_config()
        odr = config.odr
        n = int(round(WINDOW_S * odr))   # samples in the window
        print(f"{board.info.name}: {odr:g} Hz, +/-{config.acc_fs:g} g, "
              f"{config.samples_per_event} samples per event")

        z = np.zeros(n)                       # Z acceleration in g, ring buffer
        idx = np.full(n, -1, dtype=np.int64)  # sample number stored in each slot
        latest = [-1]                         # newest sample number received
        lock = threading.Lock()

        @board.on("accel")
        def on_accel(first_sample, xyz):
            zs = np.asarray(xyz, dtype=np.float64).reshape(-1, 3)[:, 0] / 1000.0
            samples = first_sample + np.arange(len(zs))
            with lock:
                z[samples % n] = zs
                idx[samples % n] = samples
                latest[0] = max(latest[0], int(samples[-1]))

        fig, ax = plt.subplots(figsize=(10, 4))
        t = (np.arange(n) - (n - 1)) / odr      # -5 s ... 0 s
        (line,) = ax.plot(t, np.full(n, np.nan), lw=0.8)
        ax.set_xlim(t[0], 0)
        ax.set_ylim(-1.5, 1.5)
        ax.set_xlabel("time (s)")
        ax.set_ylabel("Z acceleration (g)")
        ax.grid(True, alpha=0.3)
        fig.tight_layout()

        def update(_frame):
            with lock:
                last = latest[0]
                if last < 0:
                    return (line,)
                wanted = last - (n - 1) + np.arange(n)   # sample numbers in the window, oldest first
                slots = wanted % n
                y = np.where(idx[slots] == wanted, z[slots], np.nan)   # NaN = not received
            line.set_ydata(y)

            # grow the y range to fit the data, never shrink below ±1.5 g
            if np.isfinite(y).any():
                lo, hi = np.nanmin(y), np.nanmax(y)
                ylo, yhi = ax.get_ylim()
                if lo < ylo or hi > yhi:
                    ax.set_ylim(min(ylo, lo - 0.1), max(yhi, hi + 0.1))
                    fig.canvas.draw_idle()
            ax.set_title(f"sample {last}   events dropped: {board.dropped}")
            return (line,)

        anim = FuncAnimation(fig, update, interval=1000 / FPS, cache_frame_data=False)
        plt.show()   # blocks until the window is closed

        board.off("accel")
        del anim


if __name__ == "__main__":
    main()
