"""Lecture 20, an airliner with all engines out: the jet transport of Lectures 12-17 (_transport.py) at an assumed 230 t,
gliding from 11 km to sea level in the ISA, flown four ways: at C_L* (flattest glide) in still air; at the least-sink
C_L = sqrt(3) C_L* in still air; at C_L* into a 50 kt headwind; and at the speed to fly for that headwind at each height
(flight.performance.glide_state, speed_to_fly). A runway 200 km away (hypothetical) is marked.
Writes img/anim-20-airliner.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _transport as T
from flight import performance as PF, aero as AE, atmosphere as A
from flight.constants import G0, KT

MASS = 230e3
W = MASS * G0
H0 = 11000.0
WIND = 50 * KT
TARGET = 200e3
CLS, E_MAX = AE.max_lift_to_drag(T.CD0, T.K)
CLM = PF.min_sink_cl(T.CD0, T.K)
HS = np.linspace(H0, 0.0, 2201)


def fly(speed, wind):
    """March down in height; speed(rho) is the airspeed flown. Returns arrays of height, distance, time."""
    x = t = 0.0
    xs, ts = [0.0], [0.0]
    for h0, h1 in zip(HS[:-1], HS[1:]):
        rho = A.isa(0.5 * (h0 + h1))[2]
        V = speed(rho)
        cl = W / (0.5 * rho * V**2 * T.S)
        _, _, sink, vh = PF.glide_state(W, rho, T.S, cl, AE.parabolic_cd(cl, T.CD0, T.K))
        dt = (h0 - h1) / sink
        t += dt; x += (vh - wind) * dt
        xs.append(x); ts.append(t)
    return np.array(xs), np.array(ts)


AT_CL = lambda cl: (lambda rho: PF.speed_for_cl(W, rho, T.S, cl))
RUNS = {"flattest glide, still air": (fly(AT_CL(CLS), 0.0), BLUE, "-"),
        "least sink, still air": (fly(AT_CL(CLM), 0.0), GREEN, "-"),
        "flattest-glide speed, 50 kt headwind": (fly(AT_CL(CLS), WIND), MAROON, "--"),
        "speed to fly, 50 kt headwind": (fly(lambda rho: PF.speed_to_fly(W, rho, T.S, T.CD0, T.K, WIND), WIND), AMBER, "-")}
RESULT = {k: (r[0][0][-1], r[0][1][-1]) for k, r in RUNS.items()}       # distance (m), time (s)
V_TOP = PF.speed_for_cl(W, A.isa(H0)[2], T.S, CLS)
EAS = PF.speed_for_cl(W, 1.225, T.S, CLS)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(11, 5))
    fig.subplots_adjust(bottom=0.14)
    N = 70
    T_END = max(r[1] for r in RESULT.values())
    TIMES = np.linspace(0, T_END, N)

    def frame(k):
        ax.clear()
        tk = TIMES[k]
        for lab, ((x, t), c, ls) in RUNS.items():
            j = min(np.searchsorted(t, tk), len(t) - 1)
            ax.plot(x[:j + 1] / 1e3, HS[:j + 1] / 1e3, color=c, lw=2.4, ls=ls, label=f"{lab}: {x[-1] / 1e3:.0f} km")
            ax.plot(x[j] / 1e3, HS[j] / 1e3, "o", color=c, ms=7)
        ax.axvline(TARGET / 1e3, color=GREY, lw=1.2, ls=":"); ax.text(TARGET / 1e3 + 2, 10.3, "runway", color=GREY, fontsize=12)
        ax.set_xlim(0, 230); ax.set_ylim(0, 11.5); ax.set_xlabel("distance (km)"); ax.set_ylabel("altitude (km)")
        ax.set_title(f"{tk / 60:.1f} min after the engines stop", fontsize=13, loc="left")
        ax.legend(frameon=False, fontsize=11, loc="upper right")
        for s in ("top", "right"):
            ax.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 10, "anim-20-airliner", dpi=90, hold=2.5)
