"""Lecture 24, two full turns of Hull's SBJ at 20,000 ft and 11,000 lb with full thrust (P = 0.98), on the course
simulator (flat-Earth form, Lecture 7): (1) the best sustained turn, at C_Lmax and Sadraey's corner velocity (eq. 9.47),
where the full thrust just balances the drag; (2) a maximum-performance turn entered at Hull's corner speed (eq. 7.57),
at the 4.5 g limit or C_Lmax, whichever is lower, with the bank set so that (L + T sin(alpha)) cos(sigma) = W. The second turn is quicker
but bleeds speed. Plan view (left), airspeed (right). Writes img/anim-24-bleed.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, INK, GREY
import _turns as T
import _climb as C
from flight import performance as PF, atmosphere as A, simulate, eom
from flight.constants import FT, G0

H = 20000 * FT
RHO = A.isa(H)[2]
VS = T.sbj_stall(H)
CD0, K = C.polar(T.SBJ)
V_SUST = PF.sustained_corner_speed(C.thrust(T.SBJ, H), RHO, T.SBJ.aero.S, CD0, K, T.CLMAX_SBJ)
V_CORNER = PF.corner_speed(VS, T.N_LIM_SBJ)


class TurnAtLimit:
    """Level turn at the largest load factor allowed by n_lim and by C_Lmax at the current speed; full thrust."""

    def __init__(self, n_lim):
        self.n_lim = n_lim

    def __call__(self, s):
        n = min(self.n_lim, PF.stall_load_factor(s.V, VS))
        alpha = 0.0
        for _ in range(3):              # lift plus the thrust's normal component, T sin(alpha), must equal n W
            cl = PF.cl_for_load_factor(n - s.thrust_max * np.sin(alpha) / s.weight, s.weight, s.rho, s.V, s.aero.S)
            alpha = s.aero.alpha_for_cl(cl, s.mach)
        return alpha, PF.bank_for_load_factor(max(n, 1.0)), 1.0


def full_circle(t, y):
    return y[5] - 2 * np.pi


full_circle.direction = 1


def fly(V0):
    return simulate.simulate(T.SBJ, dict(h=H, V=V0, gamma_deg=0.0, chi_deg=0.0, m=T.W_SBJ / G0), TurnAtLimit(T.N_LIM_SBJ),
                             eom.Options(gravity="flat"), t_end=200.0, max_step=0.05, form="flat", stops=(full_circle,))


RUNS = [("best sustained", fly(V_SUST), BLUE), ("from the corner speed", fly(V_CORNER), MAROON)]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.0), gridspec_kw=dict(width_ratios=[1.1, 1]))
    fig.subplots_adjust(wspace=0.3, bottom=0.16)
    T_END = max(tr.t[-1] for _, tr, _ in RUNS)
    N = 110
    times = np.linspace(0, T_END, N)

    def frame(k):
        a1.clear(); a2.clear()
        t = times[k]
        for name, tr, c in RUNS:
            m = tr.t <= t
            a1.plot(tr.y[m] / 1e3, tr.x[m] / 1e3, color=c, lw=2.4)
            a1.plot(tr.y[m][-1] / 1e3, tr.x[m][-1] / 1e3, "o", color=c, ms=8)
            a2.plot(tr.t[m], tr.V[m], color=c, lw=2.4, label=f"{name}:\n360° in {tr.t[-1]:.1f} s")
        a1.plot(0, 0, "^", color=INK, ms=9)
        a1.set_aspect("equal"); a1.set_xlim(-0.2, 1.5); a1.set_ylim(-0.75, 0.85)
        a1.set_xlabel("east (km)"); a1.set_ylabel("north (km)")
        a2.set_xlim(0, T_END * 1.02); a2.set_ylim(100, 205)
        a2.set_xlabel("time (s)"); a2.set_ylabel("airspeed (m/s)")
        a2.text(T_END, 198, f"t = {t:4.1f} s", ha="right", fontsize=11)
        a2.legend(frameon=False, fontsize=11, loc="upper right", bbox_to_anchor=(1.0, 0.92))
        despine(a1); despine(a2)
        return []

    save_anim(fig, frame, N, 12, "anim-24-bleed", hold=2.5)
