"""Lecture 29, the first three stages of the PSLV model from Sriharikota with pitch-overs of 6.0, 7.2 (reference) and
8.4 degrees: height against distance along the ground, drawn in time. Writes img/anim-29-kick.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN
import _ascent as AS

CASES = [dict(kick=k, c=c, **AS.boost(k)) for k, c in zip(AS.KICKS, (GREEN, BLUE, MAROON))]
N = 90

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.0))
    ax.set_xlim(0, 1.05 * max(c["downrange"] for c in CASES) / 1e3); ax.set_ylim(0, 640)
    ax.set_xlabel("distance along the ground (km)"); ax.set_ylabel("height (km)"); despine(ax)
    lines, dots = [], []
    for c in CASES:
        lines.append(ax.plot([], [], color=c["c"], lw=2.4, label=f"{c['kick']}°: PS3 out at {c['h'] / 1e3:.0f} km, "
                             f"{c['V'] / 1e3:.2f} km/s, {np.degrees(c['gamma']):.0f}° climb")[0])
        dots.append(ax.plot([], [], "o", color=c["c"], ms=8)[0])
    ax.legend(handles=lines, frameon=False, fontsize=10, loc="upper left", title="pitch-over", title_fontsize=10)
    clock = ax.text(0.98, 0.05, "", transform=ax.transAxes, ha="right", fontsize=11)
    fig.subplots_adjust(left=0.1, right=0.98, bottom=0.15, top=0.97)

    def frame(k):
        now = AS.T_PS3_SEP * k / (N - 1)
        for c, ln, dt in zip(CASES, lines, dots):
            m = (c["tr"].t <= now + 1e-9)
            ln.set_data(c["tr"].downrange[m] / 1e3, c["tr"].h[m] / 1e3)
            dt.set_data([c["tr"].downrange[m][-1] / 1e3], [c["tr"].h[m][-1] / 1e3])
        clock.set_text(f"t = {now:.0f} s")
    save_anim(fig, frame, N, 15, "anim-29-kick")
