"""Lecture 20, speed to fly in moving air for Ojha's glider at 2 km: the small-angle hodograph (Ojha eq. 7.14) with the
tangents from the origin (still air), from (V_w, 0) for a headwind of 8 m/s, and from (0, -1.5) for air sinking at
1.5 m/s (flight.performance.speed_to_fly). Writes img/fig-20-moving-air.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK
import _ojha as O
from flight import performance as PF, atmosphere as A

G = O.GLIDER
RHO = A.isa(2000.0)[2]
V = np.linspace(18, 60, 400)
SINK = PF.sink_rate_small_angle(V, G["W"], RHO, G["S"], G["CD0"], G["K"])
HEADWIND, AIR_SINK = 8.0, 1.5
CASES = {"still air": (0.0, 0.0, BLUE), "headwind 8 m/s": (HEADWIND, 0.0, GREEN), "air sinking 1.5 m/s": (0.0, AIR_SINK, AMBER)}
BEST = {k: PF.speed_to_fly(G["W"], RHO, G["S"], G["CD0"], G["K"], w, s) for k, (w, s, _) in CASES.items()}


def sink(v):
    return PF.sink_rate_small_angle(v, G["W"], RHO, G["S"], G["CD0"], G["K"])


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ax.plot(V, -SINK, color=MAROON, lw=2.7, label="hodograph")
    for k, (w, s, c) in CASES.items():
        vb = BEST[k]
        x0, y0 = w, -s
        xs = np.array([x0, 60])
        ax.plot(xs, y0 + (xs - x0) * (-sink(vb) - y0) / (vb - x0), color=c, lw=1.8, ls="--")
        ax.plot(x0, y0, "s", color=c, ms=7)
        ax.plot(vb, -sink(vb), "o", color=c, ms=9, label=f"{k}: fly at {vb:.1f} m/s")
    ax.set_xlim(-1, 60); ax.set_ylim(-4, 0.3); ax.axhline(0, color=INK, lw=0.6); ax.axvline(0, color=INK, lw=0.6)
    ax.set_xlabel("horizontal airspeed (m/s)"); ax.set_ylabel("vertical speed (m/s)")
    ax.legend(frameon=False, fontsize=12, loc="lower left")
    despine(ax)
    save(fig, "fig-20-moving-air")
