"""Lecture 19, accelerating through Mach 1 (after Filippone, Fig. 8.14): the Tejas-class model at 11 km and 8500 kg with
full afterburner from Mach 0.9 to 1.6 in level flight (flight.performance.accelerate_level). Left: thrust and drag
against Mach number, with the excess thrust shaded up to the present Mach number. Right: Mach number and the
acceleration in g against time. Writes img/anim-19-accelerate.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, AMBER, INK
import _fighter as F

V, MASS, H = F.TEJ, F.M_REF, 11000.0
M0, M1 = 0.9, 1.6
RUN = F.accelerate(V, M0, M1, MASS, H)
MM = np.linspace(0.8, 1.8, 300)
_tr = RUN["M"] < 1.4
I_SLOW = int(np.argmin(np.where(_tr, RUN["accel"], 9.0)))          # the transonic dip
I_PEAK = I_SLOW + int(np.argmax(RUN["accel"][I_SLOW:]))              # the supersonic recovery
T_TOTAL, FUEL, DIST = RUN["t"][-1], MASS - RUN["m"][-1], RUN["x"][-1]
T_TO_1 = float(np.interp(1.0, RUN["M"], RUN["t"]))
T_TRANS = float(np.interp(1.2, RUN["M"], RUN["t"]) - np.interp(1.0, RUN["M"], RUN["t"]))

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.9))
    fig.subplots_adjust(wspace=0.32, bottom=0.14)
    a2b = None
    N = 70
    idx = np.linspace(0, len(RUN["M"]) - 1, N).astype(int)

    def frame(k):
        global a2b
        a1.clear(); a2.clear()
        if a2b is not None:
            a2b.remove()
        j = idx[k]
        Mj, mj = RUN["M"][j], RUN["m"][j]
        T = np.array([F.thrust(V, x, H) for x in MM]) / 1e3
        D = np.array([F.drag(V, x, mj, H) for x in MM]) / 1e3
        a1.plot(MM, T, color=BLUE, lw=2.4, label="thrust (afterburner)")
        a1.plot(MM, D, color=MAROON, lw=2.4, label="drag")
        sel = (MM >= M0) & (MM <= Mj)
        a1.fill_between(MM[sel], D[sel], T[sel], color=GREEN, alpha=0.25)
        a1.axvline(Mj, color=INK, lw=1)
        a1.set_xlim(0.8, 1.8); a1.set_ylim(0, 75); a1.set_xlabel("Mach number"); a1.set_ylabel("force (kN)")
        a1.set_title(f"Mach {Mj:.2f}, {RUN['t'][j]:.0f} s, {MASS - mj:.0f} kg of fuel", fontsize=13, loc="left")
        a1.legend(frameon=False, fontsize=12, loc="upper left")
        a2.plot(RUN["t"][:j + 1], RUN["M"][:j + 1], color=INK, lw=2.5)
        a2.set_xlim(0, T_TOTAL * 1.05); a2.set_ylim(0.85, 1.65); a2.set_xlabel("time (s)"); a2.set_ylabel("Mach number")
        a2b = a2.twinx()
        a2b.plot(RUN["t"][:j + 1], RUN["accel"][:j + 1], color=AMBER, lw=2.2, ls="--")
        a2b.set_ylim(0, 0.4); a2b.set_ylabel("acceleration ($g$)", color=AMBER)
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 12, "anim-19-accelerate", dpi=90, hold=2.5)
