"""Lecture 10, an airliner climbs on a 'constant CAS, then constant Mach' schedule (280 kt, then Mach 0.78): the
calibrated airspeed, the equivalent airspeed, the true airspeed and the Mach number as the altitude rises to 12 km.
From flight.airspeed (crossover_altitude, schedule_mach). Writes img/anim-10-climb.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import airspeed as AS, atmosphere as A
from flight.constants import KT

VC, MACH = 280 * KT, 0.78
H = np.linspace(0.0, 12000.0, 241)
HX = AS.crossover_altitude(VC, MACH)
ROWS = []
for h in H:
    t, p, rho = A.isa(h)
    M = AS.schedule_mach(VC, MACH, h)
    V = M * A.speed_of_sound(t)
    ROWS.append((AS.cas_from_impact(p * AS.impact_ratio(M)) / KT, AS.eas_from_tas(V, rho) / KT, V / KT, M))
ROWS = np.array(ROWS)

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.6), sharey=True, gridspec_kw=dict(width_ratios=[2.2, 1]))
    fig.subplots_adjust(bottom=0.14, top=0.9, wspace=0.08)
    N = 100
    ks = np.linspace(0, len(H) - 1, N).astype(int)

    def frame(k):
        j = ks[k]
        a1.clear(); a2.clear()
        for col, c, lab in ((0, INK, "CAS"), (1, GREEN, "EAS"), (2, MAROON, "TAS")):
            a1.plot(ROWS[:j + 1, col], H[:j + 1] / 1e3, color=c, lw=2.4, label=lab)
            a1.plot(ROWS[j, col], H[j] / 1e3, "o", color=c, ms=6)
        a2.plot(ROWS[:j + 1, 3], H[:j + 1] / 1e3, color=BLUE, lw=2.4)
        a2.plot(ROWS[j, 3], H[j] / 1e3, "o", color=BLUE, ms=6)
        for a in (a1, a2):
            a.axhline(HX / 1e3, color=GREY, lw=0.8, ls="--")
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        a1.text(330, HX / 1e3 + 0.25, f"crossover {HX / 1e3:.1f} km", fontsize=11, color=GREY)
        a1.set_xlim(200, 480); a2.set_xlim(0.4, 0.85); a1.set_ylim(0, 12.5)
        a1.set_xlabel("airspeed (kt)"); a2.set_xlabel("Mach number"); a1.set_ylabel("altitude (km)")
        a1.legend(frameon=False, fontsize=11, loc="lower right")
        a1.set_title(f"CAS {ROWS[j, 0]:.0f} kt   EAS {ROWS[j, 1]:.0f} kt   TAS {ROWS[j, 2]:.0f} kt", fontsize=12, loc="left")
        a2.set_title(f"M {ROWS[j, 3]:.3f}", fontsize=12, loc="left")
        return []

    save_anim(fig, frame, N, 12, "anim-10-climb", hold=2.5)
