"""Lecture 26, Hull's SBJ taking off on a hot day at Mumbai (May, 33.7 C, 12 m) and at Leh (July, 28.5 C, 3256 m): the
ground run (full force balance, average thrust scaled by sigma^1.2) and Hull's transition at n = 1.2 to the 35 ft screen,
against time, with each runway drawn to scale. The height is exaggerated 8 times. Writes img/anim-26-takeoff.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREY, AMBER
import _takeoff as T
from flight import performance as PF
from flight.constants import G0, RHO0_SL


def track(field):
    rho = T.airfield_state(field)[2]
    th = T.T_AVG * (rho / RHO0_SL)**T.A_LAPSE
    r = T.takeoff(rho)
    V = np.linspace(0.5, r["vlo"], 50)
    xt = [PF.ground_run_numeric(lambda v: T.net_force(v, rho, th, T.TO), T.M, 0.0, vk, n=400) for vk in V]
    x, t = np.array([0.0] + [a for a, b in xt]), np.array([0.0] + [b for a, b in xt])
    tt = np.linspace(0, r["t_total"] - r["t_ground"], 30)[1:]
    xa = x[-1] + r["vlo"] * tt
    ha = 0.5 * G0 * (T.TO["n"] - 1) * tt**2               # h = g (n - 1) t^2 / 2 at constant V and n (Hull sec. 6.6)
    return dict(field=field, r=r, t=np.concatenate([t, t[-1] + tt]), x=np.concatenate([x, xa]),
                h=np.concatenate([np.zeros_like(x), ha]))


TRACKS = [(track(T.MUMBAI), BLUE, 0.0), (track(T.LEH), MAROON, -40.0)]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(11, 4.2))
    fig.subplots_adjust(bottom=0.2, top=0.95)
    T_END = max(tr["t"][-1] for tr, _, _ in TRACKS)
    N = 100
    times = np.linspace(0, T_END, N)

    def frame(k):
        ax.clear()
        for tr, c, y0 in TRACKS:
            f = tr["field"]
            ax.plot([0, f["runway"] / 1e3], [y0, y0], color=GREY, lw=6, solid_capstyle="butt", alpha=0.5)
            m = tr["t"] <= times[k]
            x, h = tr["x"][m] / 1e3, y0 + 8 * tr["h"][m]
            ax.plot(x, h, color=c, lw=2.6)
            ax.plot(x[-1], h[-1], "o", color=c, ms=8)
            ax.text(-0.05, y0 + 6, f"{f['name']}, {f['temp_c']} °C", ha="right", fontsize=11, color=c)
            if k == N - 1:
                ax.text(tr["x"][-1] / 1e3, y0 + 8 * tr["h"][-1] + 8, f"35 ft at {tr['r']['total']:.0f} m", fontsize=11, color=c,
                        ha="center")
        ax.text(2.95, 110, f"t = {times[k]:4.1f} s", ha="right", fontsize=11)
        ax.set_xlim(-0.9, 3.0); ax.set_ylim(-60, 125); ax.set_yticks([])
        ax.set_xlabel("distance from brake release (km); height exaggerated 8 times")
        for s in ("top", "right", "left"):
            ax.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 12, "anim-26-takeoff", hold=2.5)
