"""Lecture 23, the coffin corner: the DC-9-class airliner of fig-23-buffet climbing from 20,000 ft; the low-speed and
high-speed 1.3 g buffet Mach numbers close in until they meet at the corner. Left: buffet boundary and the C_L needed.
Right: the two buffet Mach numbers against altitude, traced. Writes img/anim-23-coffin.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, INK, GREY
from _scripts import load
import _dc9 as D
from flight import performance as PF, atmosphere as A
from flight.constants import FT

BF = load("fig-23-buffet")
HS = np.linspace(20000 * FT, BF.H_CORNER - 15.0, 60)
TRACE = [PF.buffet_machs(D.N_BUFFET, BF.W, D.S, A.isa(h)[1], BF.cl_buffet) for h in HS]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.9))
    fig.subplots_adjust(wspace=0.28, bottom=0.14)
    M = np.linspace(0.3, 0.9, 300)

    def frame(k):
        a1.clear(); a2.clear()
        h = HS[k]
        a1.plot(BF.MB, BF.CB, color=INK, lw=2.6)
        a1.plot(M, D.N_BUFFET * BF.W / (0.7 * A.isa(h)[1] * M**2 * D.S), color=MAROON, lw=2.0, ls="--")
        for mb in TRACE[k]:
            a1.plot(mb, BF.cl_buffet(mb), "o", color=MAROON, ms=8)
        a1.set_xlim(0.3, 0.9); a1.set_ylim(0, 1.6); a1.set_xlabel("Mach number"); a1.set_ylabel("lift coefficient")
        a1.set_title(f"{h / FT:,.0f} ft", fontsize=13, loc="left")
        lows = [t[0] if len(t) else np.nan for t in TRACE[:k + 1]]
        highs = [t[-1] if len(t) else np.nan for t in TRACE[:k + 1]]
        a2.plot(lows, HS[:k + 1] / FT / 1000, color=BLUE, lw=2.5, label="low-speed buffet")
        a2.plot(highs, HS[:k + 1] / FT / 1000, color=MAROON, lw=2.5, label="high-speed buffet")
        a2.set_xlim(0.4, 0.85); a2.set_ylim(19, 36); a2.set_xlabel("Mach number"); a2.set_ylabel("altitude (1000 ft)")
        a2.legend(frameon=False, fontsize=11, loc="lower left")
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(HS), 10, "anim-23-coffin", dpi=90, hold=2.5)
