"""Lecture 7: the HANSA-3's best glide from 1500 m (as anim-07-glide.py) on the course simulator, in its main (Cartesian) form with the Earth's rotation off (the flat
form ignores wind), in
still air, a 10 m/s headwind and a 10 m/s tailwind (flight.wind.ConstantWind), each started with the same velocity
through the air. Top: height against distance over the ground. Bottom: height against distance through the air.
Writes img/fig-07-glide-wind.png."""
import numpy as np
from scipy.integrate import cumulative_trapezoid
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import vehicle, guidance, simulate, eom, atmosphere, wind
from flight.constants import G0, R_EARTH
from flight.performance import best_glide, glide_angle, speed_for_cl

H0, WIND = 1500.0, 10.0
V_ = vehicle.load("hansa-3")
CL, E = best_glide(V_.aero.cd0(0.1), V_.aero.k(0.1))
GAM = glide_angle(E)
VA0 = speed_for_cl(V_.gross_mass * G0 * np.cos(GAM), atmosphere.ISA.state(H0)[2], V_.aero.S, CL)


def fly(tailwind):
    """The glide heading north with a steady wind of `tailwind` m/s from behind (negative: headwind)."""
    vx, vz = VA0 * np.cos(GAM) + tailwind, VA0 * np.sin(GAM)
    kw = dict(coriolis=False, centrifugal=False, gravity="point", earth="sphere")
    if tailwind:
        kw["wind"] = wind.ConstantWind(abs(tailwind), 180.0 if tailwind > 0 else 0.0)
    tr = simulate.simulate(V_, dict(h=H0, V=float(np.hypot(vx, vz)), gamma_deg=float(np.degrees(np.arctan2(vz, vx))), chi_deg=0.0,
                                    lat_deg=0.0, lon_deg=0.0), guidance.ConstantCL(CL), eom.Options(**kw), t_end=3000, max_step=1.0)
    air = np.concatenate([[0], cumulative_trapezoid(np.sqrt(np.clip(tr.Va**2 - np.gradient(tr.h, tr.t)**2, 0, None)), tr.t)])
    return dict(t=tr.t, h=tr.h, ground=R_EARTH * np.hypot(tr.lat - tr.lat[0], tr.lon - tr.lon[0]), air=air, Va=tr.Va)


RUNS = [(lab, c, ls, fly(w)) for w, lab, c, ls in ((0.0, "still air", INK, "-"), (-WIND, "10 m/s headwind", MAROON, "--"), (WIND, "10 m/s tailwind", BLUE, ":"))]

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 6.2), sharex=True)
    fig.subplots_adjust(hspace=0.28)
    for lab, c, ls, r in RUNS:
        a.plot(r["ground"] / 1e3, r["h"], color=c, lw=2.6, label=f"{lab}: {r['ground'][-1] / 1e3:.1f} km in {r['t'][-1]:.0f} s")
    for (lab, c, ls, r), lw in zip(RUNS, (7.0, 3.6, 1.8)):
        b.plot(r["air"] / 1e3, r["h"], color=c, lw=lw, ls=ls if lw < 7 else "-", alpha=0.45 if lw == 7 else 1)
    a.set_title("over the ground", fontsize=12.5); b.set_title(f"through the air: three lines on top of each other, {RUNS[0][3]['air'][-1] / 1e3:.1f} km", fontsize=12.5)
    b.set_xlabel("horizontal distance (km)")
    for ax in (a, b):
        ax.set_ylabel("height (m)"); ax.set_ylim(0, 1600); despine(ax)
    a.legend(frameon=False, fontsize=11, loc="upper right")
    save(fig, "fig-07-glide-wind")
