"""Lecture 28: the PSLV-CA of the course vehicle file with 1 t payload (flight.rocket.stage_table): the stack losing
propellant and dropping stages, its mass (log axis) and the ideal velocity, no losses, against burning time with the
coasts left out. Writes img/anim-28-pslv-staging.gif."""
import numpy as np
from matplotlib.patches import Rectangle
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import rocket as R, vehicle

PSLV = vehicle.load("pslv-ca")
ROWS = R.stage_table(PSLV)
COL = [MAROON, BLUE, GREEN, AMBER]
NAMES = ["PS1", "PS2", "PS3", "PS4"]
T0 = np.concatenate([[0], np.cumsum([r["burn"] for r in ROWS])])


def state(t):
    """(stage index, propellant fraction left, mass kg, ideal velocity m/s) at burning time t."""
    k = int(min(np.searchsorted(T0, t, side="right") - 1, 3))
    f = min((t - T0[k]) / ROWS[k]["burn"], 1.0)
    r = ROWS[k]
    m = r["m0"] + f * (r["m1"] - r["m0"])
    v = sum(x["dv"] for x in ROWS[:k]) + R.delta_v(r["ve"], r["m0"], m)
    return k, 1 - f, m, v


# plot samples with both sides of every separation
TT = np.concatenate([np.linspace(T0[k], T0[k + 1] - 1e-6, 120) for k in range(4)])
TT[-1] = T0[-1]
MM = np.array([state(t)[2] for t in TT])
VV = np.array([state(t)[3] for t in TT])

if __name__ == "__main__":
    fig = plt.figure(figsize=(10.5, 5.6))
    s = fig.add_axes([0.02, 0.1, 0.17, 0.82]); a = fig.add_axes([0.32, 0.57, 0.65, 0.36]); b = fig.add_axes([0.32, 0.12, 0.65, 0.36])
    frames = np.concatenate([np.linspace(T0[k], T0[k + 1] - 1e-6, n) for k, n in zip(range(4), (22, 22, 20, 36))])
    frames[-1] = T0[-1]
    HEIGHT = [4.0, 2.4, 1.5, 1.0]

    def frame(i):
        t = frames[i]; k, left, m, v = state(t)
        for ax in (s, a, b):
            ax.clear()
        y = 0.0
        for j in range(k, 4):
            s.add_patch(Rectangle((0.25, y), 0.5, HEIGHT[j], facecolor="none", edgecolor=COL[j], lw=2))
            s.add_patch(Rectangle((0.25, y), 0.5, HEIGHT[j] * (left if j == k else 1.0), facecolor=COL[j], alpha=0.75))
            s.text(0.8, y + HEIGHT[j] / 2, NAMES[j], va="center", fontsize=11, color=COL[j])
            y += HEIGHT[j]
        s.add_patch(Rectangle((0.38, y), 0.24, 0.35, facecolor=INK))
        s.set_xlim(0, 1.15); s.set_ylim(-0.2, 9.6); s.axis("off"); s.set_title(f"{m / 1e3:.2f} t", fontsize=13)
        sel = TT <= t + 1e-9
        a.plot(TT[sel], MM[sel] / 1e3, color=INK, lw=2.4); a.plot(t, m / 1e3, "o", color=COL[k], ms=8)
        b.plot(TT[sel], VV[sel] / 1e3, color=INK, lw=2.4); b.plot(t, v / 1e3, "o", color=COL[k], ms=8)
        a.set_yscale("log"); a.set_ylim(1, 400); a.set_ylabel("mass (t)"); a.set_xticklabels([])
        b.set_ylim(0, 12); b.set_ylabel("ideal speed (km/s)"); b.set_xlabel("burning time, coasts left out (s)")
        b.text(0.03, 0.82, f"{v / 1e3:.2f} km/s", transform=b.transAxes, fontsize=13)
        for ax in (a, b):
            ax.set_xlim(0, T0[-1] * 1.02); despine(ax)
            for j in range(1, 4):
                ax.axvline(T0[j], color=GREY, lw=0.8, ls=":")
        return []

    save_anim(fig, frame, len(frames), 10, "anim-28-pslv-staging", dpi=90, hold=2.5)
