"""Lecture 5, the terms of the gamma equation during the reference PSLV ascent on the course simulator
(flight/missions.py): gravity, curvature, Coriolis and centrifugal terms of V gamma-dot, from the engine's
eom.term_breakdown along the simulated path. As the speed builds up the curvature term grows until, in orbit,
the four together cancel. Writes img/anim-05-terms.gif."""
import numpy as np
from _visual import plt, save_anim, despine, INK, MAROON, BLUE, GREEN, AMBER, PURPLE, GREY
from flight import missions, frames
from flight.eom import term_breakdown

TR = missions.fly(missions.pslv_c18_like())
KEYS = [("gravity", PURPLE), ("curvature", AMBER), ("coriolis", GREEN), ("centrifugal", BLUE)]
LABEL = dict(gravity="gravity", curvature="curvature", coriolis="Coriolis", centrifugal="centrifugal")


def terms_at(i):
    r, lat, lon = frames.spherical_from_ecef(TR.r[i])
    t = term_breakdown(r, lat, lon, TR.V[i], TR.gamma[i], TR.chi[i])
    return np.array([t[k][1] for k, _ in KEYS])


IDX = np.unique(np.concatenate([np.searchsorted(TR.t, np.linspace(5, TR.t[-1], 120)), [len(TR.t) - 1]]))
VALS = np.array([terms_at(i) for i in IDX])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    fig.subplots_adjust(left=0.2, right=0.97)

    def frame(k):
        ax.clear()
        i = IDX[k]
        v = VALS[k]
        y = np.arange(len(KEYS))[::-1]
        for yi, val, (name, c) in zip(y, v, KEYS):
            ax.barh(yi, val, color=c, height=0.6)
            ax.text(val + (0.15 if val >= 0 else -0.15), yi, f"{val:+.3f}", va="center", ha="left" if val >= 0 else "right",
                    fontsize=12, color=c)
        ax.barh(-1.2, v.sum(), color=INK, height=0.6)
        ax.text(v.sum() + (0.15 if v.sum() >= 0 else -0.15), -1.2, f"{v.sum():+.3f}", va="center",
                ha="left" if v.sum() >= 0 else "right", fontsize=12)
        ax.set_yticks(list(y) + [-1.2])
        ax.set_yticklabels([LABEL[n] for n, _ in KEYS] + ["sum: $V\\dot\\gamma$\nwith no lift"], fontsize=12)
        ax.axvline(0, color=GREY, lw=1)
        ax.set_xlim(-11.5, 11.5)
        ax.set_xlabel("term of $V\\dot\\gamma$  (m/s²)")
        ax.set_title(f"PSLV on the simulator: t = {TR.t[i]:4.0f} s,  h = {TR.h[i] / 1e3:5.0f} km,  "
                     f"V = {TR.V[i] / 1e3:4.2f} km/s,  $\\gamma$ = {np.degrees(TR.gamma[i]):4.1f}°", fontsize=12)
        despine(ax)
        return []

    save_anim(fig, frame, len(IDX), 12, "anim-05-terms", hold=2.5)
