"""Lecture 7, two glides from 1500 m on the course simulator (flat form, constant lift coefficient at the best
glide): the HAL Hansa-3 trainer with its engine stopped (estimated polar of the vehicle file) and a representative
glider with E = 40. Writes img/anim-07-glide.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREY
from flight import vehicle, guidance, simulate, eom, atmosphere
from flight.constants import G0
from flight.performance import best_glide, glide_angle, speed_for_cl

H0 = 1500.0


def glide(name):
    v = vehicle.load(name)
    cl, E = best_glide(v.aero.cd0(0.1), v.aero.k(0.1))
    V0 = speed_for_cl(v.gross_mass * G0 * np.cos(glide_angle(E)), atmosphere.ISA.state(H0)[2], v.aero.S, cl)
    tr = simulate.simulate(v, dict(h=H0, V=V0, gamma_deg=np.degrees(glide_angle(E)), chi_deg=0.0), guidance.ConstantCL(cl),
                           eom.Options(), t_end=3000, max_step=1.0, form="flat")
    return tr, E


RUNS = [("Hansa-3, engine off", *glide("hansa-3"), MAROON), ("glider, $E$ = 40", *glide("glider-representative"), BLUE)]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.6))
    T = max(tr.t[-1] for _, tr, _, _ in RUNS)
    N = 120
    times = np.linspace(0, T, N)

    def frame(k):
        ax.clear()
        t = times[k]
        for (name, tr, E, c), dy in zip(RUNS, (380, 110)):
            m = tr.t <= t
            ax.plot(tr.x[m] / 1e3, tr.h[m], color=c, lw=2.4)
            ax.plot(tr.x[m][-1] / 1e3, tr.h[m][-1], "o", color=c, ms=8)
            ax.text(tr.x[m][-1] / 1e3 + 0.6, tr.h[m][-1] + dy, f"{name}: {tr.x[m][-1] / 1e3:.1f} km", color=c, fontsize=11,
                    ha="right" if tr.x[m][-1] > 45e3 else "left")
        ax.set_xlim(-1, 65)
        ax.set_ylim(0, 1750)
        ax.set_xlabel("distance (km)")
        ax.set_ylabel("height (m)")
        ax.text(64, 1650, f"t = {t / 60:4.1f} min", fontsize=11, ha="right")
        despine(ax)
        return []

    save_anim(fig, frame, N, 15, "anim-07-glide", hold=2.5)
