"""Lecture 27, Hull's SBJ landing on a hot day at Mumbai (May, 33.7 C) and at Leh (July, 28.5 C): from 50 ft down the 3 deg glide
slope, the flare at n = 1.2 (Hull sec. 6.6.2) and the ground run with brakes at mu = .35 and idle thrust, against time,
with each runway drawn to scale. Height exaggerated 8 times. Writes img/anim-27-landing.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREY
import _takeoff as T
from flight import performance as PF
from flight.constants import G0


def track(field):
    rho = T.airfield_state(field)[2]
    r = T.landing(rho)
    V, n, gl, h0 = r["vtd"], T.LAND["n"], T.LAND["glide"], T.LAND["h"]
    total, hs, xf = PF.landing_transition(V, n, gl, h0)
    xs = (h0 - hs) / gl
    x_air = np.linspace(0, total, 60)
    sq = np.sqrt(hs) - (x_air - xs) * np.sqrt(2 * G0 * (n - 1)) / (2 * V)
    h_air = np.where(x_air <= xs, h0 - gl * x_air, sq**2)
    t_air = x_air / V
    f = lambda v: T.net_force(v, rho, T.LAND["idle"], T.LAND)
    Vg = np.linspace(V, 0.5, 40)[1:]
    xt = [PF.ground_run_numeric(f, T.M, V, v, n=300) for v in Vg]
    x_g = total + np.array([a for a, b in xt])
    t_g = t_air[-1] + np.array([b for a, b in xt])
    return dict(field=field, r=r, x=np.concatenate([x_air, x_g]), h=np.concatenate([h_air, np.zeros_like(x_g)]),
                t=np.concatenate([t_air, t_g]))


TRACKS = [(track(T.MUMBAI), BLUE, 0.0), (track(T.LEH), MAROON, -60.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 + 0.05, y0 + 10, f"stops {tr['r']['total']:.0f} m from 50 ft", fontsize=11, color=c)
        ax.text(2.95, 125, f"t = {times[k]:4.1f} s", ha="right", fontsize=11)
        ax.set_xlim(-0.9, 3.0); ax.set_ylim(-80, 140); ax.set_yticks([])
        ax.set_xlabel("distance from the 50 ft point (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-27-landing", hold=2.5)
