"""Lecture 34: the representative capsule with L/D = 0.3 entering at 2 deg with its lift vector held at bank angles
0, 60 and 90 deg: the ground track (distance along and across) and the height against distance.
Writes img/anim-34-bank.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN
import _entry33 as X
from flight.constants import R_EARTH

CASES = []
for bank, c in ((0.0, GREEN), (60.0, BLUE), (90.0, MAROON)):
    tr = X.lifting(0.3, -2.0, bank)
    CASES.append(dict(bank=bank, c=c, tr=tr, along=R_EARTH * (tr.lon - tr.lon[0]) / 1e3, south=-R_EARTH * tr.lat / 1e3, **X.peaks(tr)))
T_END = max(c["tr"].t[-1] for c in CASES)
N = 90

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.6), gridspec_kw=dict(wspace=0.28))
    xmax = max(c["along"][-1] for c in CASES) * 1.03
    a.set_xlim(0, xmax); a.set_ylim(0, 105); a.set_xlabel("distance along (km)"); a.set_ylabel("height (km)")
    b.set_xlim(0, xmax); b.set_ylim(0, 1.5 * max(c["south"].max() for c in CASES))
    b.set_xlabel("distance along (km)"); b.set_ylabel("distance to the right (km)")
    despine(a); despine(b)
    arts = []
    for cs in CASES:
        l1, = a.plot([], [], color=cs["c"], lw=2.4)
        l2, = b.plot([], [], color=cs["c"], lw=2.4, label=f"bank {cs['bank']:.0f}°: {cs['load']:.1f} g")
        d, = a.plot([], [], "o", color=cs["c"], ms=8)
        arts.append((l1, l2, d))
    b.legend(handles=[x[1] for x in arts], frameon=False, fontsize=10, loc="upper left")
    fig.subplots_adjust(left=0.08, right=0.98, bottom=0.15, top=0.97)

    def frame(k):
        t = T_END * k / (N - 1)
        for cs, (l1, l2, d) in zip(CASES, arts):
            m = cs["tr"].t <= t + 1e-9
            l1.set_data(cs["along"][m], cs["tr"].h[m] / 1e3); l2.set_data(cs["along"][m], cs["south"][m])
            d.set_data([cs["along"][m][-1]], [cs["tr"].h[m][-1] / 1e3])
    save_anim(fig, frame, N, 15, "anim-34-bank")
