"""Lecture 16, three ways to fly Hull's business jet from 12,000 to 10,000 lb (_isbj.py), all starting at 35,000 ft at
the best-range speed u = 3^(1/4): (1) constant altitude and lift coefficient, the speed falls as sqrt(W);
(2) the Breguet cruise-climb, constant speed and lift coefficient, the altitude rises as the weight falls;
(3) constant altitude and speed, the lift coefficient falls (flight.performance). The weight is the clock; distance
along each path from the specific range. Writes img/anim-16-programs.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
import _isbj as J
from flight import performance as PF, aero as AE, atmosphere as A

CLR = PF.best_range_cl(J.CD0, J.K)
CDR = AE.parabolic_cd(CLR, J.CD0, J.K)
E_R = CLR / CDR
V0 = PF.speed_for_cl(J.W0, J.RHO, J.S, CLR)
H_ISO = 287.053 * 216.65 / 9.80665            # isothermal scale height above 11 km
W = np.linspace(J.W0, J.WF, 81)


def paths():
    out = {}
    # (1) constant h, C_L
    x1 = PF.range_const_alt_cl(J.RHO, J.S, CLR, CDR, J.C, J.W0, W)
    v1 = PF.speed_for_cl(W, J.RHO, J.S, CLR)
    out["constant altitude and $C_L$"] = (x1, np.zeros_like(W), v1, MAROON)
    # (2) cruise-climb: rho proportional to W, constant V
    x2 = PF.range_cruise_climb(V0, E_R, J.C, J.W0, W)
    dh = H_ISO * np.log(J.W0 / W)
    out["cruise-climb (Breguet)"] = (x2, dh, np.full_like(W, V0), BLUE)
    # (3) constant h, V
    x3 = np.array([PF.range_const_alt_speed(V0, J.RHO, J.S, J.CD0, J.K, J.C, J.W0, w) for w in W])
    out["constant altitude and speed"] = (x3, np.zeros_like(W), np.full_like(W, V0), GREEN)
    return out


PATHS = paths()

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(2, 1, figsize=(11, 6.2), sharex=True)
    fig.subplots_adjust(hspace=0.12, top=0.93, bottom=0.1)
    xmax = max(p[0][-1] for p in PATHS.values()) / J.MILE

    def frame(k):
        a1.clear(); a2.clear()
        for lab, (x, dh, v, c) in PATHS.items():
            a1.plot(x[:k + 1] / J.MILE, 35 + dh[:k + 1] / 304.8, color=c, lw=2.5, label=f"{lab}: {x[k] / J.MILE:.0f} mi")
            a2.plot(x[:k + 1] / J.MILE, v[:k + 1], color=c, lw=2.5)
            a1.plot(x[k] / J.MILE, 35 + dh[k] / 304.8, "o", color=c, ms=7)
        a1.set_ylabel("altitude (1000 ft)"); a1.set_ylim(34.5, 40.5)
        a2.set_ylabel("speed (m/s)"); a2.set_xlabel("distance (miles)"); a2.set_ylim(180, 222)
        a2.set_xlim(0, xmax * 1.03)
        a1.set_title(f"weight {W[k] / J.LB:,.0f} lb   (fuel burnt {(J.W0 - W[k]) / J.LB:,.0f} lb)", fontsize=13, loc="left")
        a1.legend(frameon=False, fontsize=11, loc="upper left")
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(W), 12, "anim-16-programs", dpi=90, hold=2.5)
