"""Lecture 27, the landing transition of Hull's SBJ at sea level (flaps 40 deg, 13,000 lb, V = 1.2 V_stall = 209 ft/s): down the
3 deg glide slope from 50 ft and a flare at constant load factor to touch-down level (Hull sec. 6.6.2, eqs. 6.44-6.50), for
n = 1.05, 1.1 and 1.2; the dot marks where the flare starts (eq. 6.47). Writes img/fig-27-flare.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, GREY
import _takeoff as T
from flight import performance as PF, atmosphere as A
from flight.constants import FT, G0

RHO = A.isa(0.0)[2]
V = 1.2 * T.stall(RHO, T.LAND["clmax"])
GL, H0 = T.LAND["glide"], T.LAND["h"]
CASES = []
for n, c in ((1.05, GREEN), (1.1, BLUE), (1.2, MAROON)):
    total, hs, xf = PF.landing_transition(V, n, GL, H0)
    xs = (H0 - hs) / GL                                     # glide-slope part
    xg = np.linspace(0, xs, 50)
    hg = H0 - GL * xg
    s = np.linspace(0, xf, 100)                             # flare: gamma = -sqrt(2 g (n-1) h)/V, so sqrt(h) falls linearly in x
    hf = (np.sqrt(hs) - s * np.sqrt(2 * G0 * (n - 1)) / (2 * V))**2
    CASES.append(dict(n=n, c=c, total=total, hs=hs, xs=xs, x=np.concatenate([xg, xs + s]), h=np.concatenate([hg, hf])))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.4))
    for cs in CASES:
        ax.plot(cs["x"], cs["h"], color=cs["c"], lw=2.4, label=f"$n$ = {cs['n']}: {cs['total']:.0f} m to touch-down")
        ax.plot(cs["xs"], cs["hs"], "o", color=cs["c"], ms=7)
    ax.axhline(0, color=GREY, lw=1)
    ax.set_xlabel("distance from the 50 ft point (m)"); ax.set_ylabel("height (m)")
    ax.set_xlim(0, 520); ax.set_ylim(-0.5, 16)
    ax.legend(frameon=False, fontsize=11, loc="upper right")
    despine(ax)
    save(fig, "fig-27-flare")
