"""Lecture 37: Hull's business jet slowing in level flight at 30,000 ft with the CG at 0.30. Above, the angle of the
elevator (drawn three times its true angle); below, the pitching-moment line for that elevator angle, sliding so that
its zero is at the angle of attack the speed needs. Mach 0.6 aerodynamics at every speed.
Writes img/anim-37-slow-down.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, INK, GREY
import _stab as S
import _airplane as AP
from flight import stability as ST
from flight.constants import DEG

V = np.linspace(200, 100, 80)
A = np.linspace(-4, 15, 60)
EXAGGERATE = 3.0


def state(speed):
    cl = S.WEIGHT / (0.5 * S.RHO * speed ** 2 * S.AREA)
    return (cl,) + ST.trim_at_cg(cl, S.XCG, S.WING, S.TAIL, S.THRUST)


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 6.4), gridspec_kw=dict(height_ratios=[1, 1.6]))
    fig.subplots_adjust(left=0.1, right=0.97, bottom=0.1, top=0.95, hspace=0.12)
    AP.body(a, S.WING.x_ac, S.TAIL.x_ac)
    AP.cg_mark(a, S.XCG, label="")
    hx, hy = S.TAIL.x_ac + 0.39, 0.30
    flap, = a.plot([], [], color=MAROON, lw=6, solid_capstyle="round", zorder=4)
    a.text(hx - 0.5, 0.52, f"elevator (angle drawn ×{EXAGGERATE:.0f})", color=MAROON, fontsize=11, ha="center")
    a.set_xlim(-1.9, S.TAIL.x_ac + 1.3); a.set_ylim(-0.45, 0.7); a.set_aspect("equal"); a.axis("off")
    cm0, cma, cmd = ST.moment_coefficients(S.XCG, S.WING, S.TAIL, S.THRUST)
    b.axhline(0, color=INK, lw=0.9); b.axvline(0, color=INK, lw=0.9)
    line, = b.plot([], [], lw=3, color=BLUE)
    dot, = b.plot([], [], "o", color=INK, ms=10, zorder=5)
    info = b.text(0.98, 0.95, "", transform=b.transAxes, ha="right", va="top", fontsize=12)
    b.set_xlim(-4, 15); b.set_ylim(-0.25, 0.3); b.set_xlabel("angle of attack (°)"); b.set_ylabel("$C_m$"); despine(b)

    def frame(k):
        cl, alpha, de = state(V[k])
        ang = EXAGGERATE * de
        flap.set_data([hx, hx + 0.34 * np.cos(ang)], [hy, hy - 0.34 * np.sin(ang)])
        line.set_data(A, cm0 + cmd * de + cma * A * DEG)
        dot.set_data([alpha / DEG], [0])
        info.set_text(f"speed {V[k]:.0f} m/s,  $C_L$ = {cl:.2f}\nangle of attack {alpha / DEG:+.1f}°\nelevator {de / DEG:+.1f}°")
    save_anim(fig, frame, len(V), 12, "anim-37-slow-down")
