"""Lecture 15: level-flight drag of the HANSA-3-class trainer at sea level at three weights (80, 100 and 120 per cent of
750 kg; the outer two are illustrative). Each least-drag point moves along a parabola of speed ~ sqrt(W), drag ~ W.
Writes img/fig-15-weight-drag.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load
from flight import performance as PF, atmosphere as A

H = load("fig-15-hansa-power")
RHO = A.isa(0.0)[2]
CASES = [(0.8, GREEN), (1.0, BLUE), (1.2, MAROON)]


def least(f):
    W = f * H.W
    v = PF.min_drag_speed(W, RHO, H.S, H.CD0, H.K)
    return v, float(np.add(*PF.level_flight_drag(W, RHO, v, H.S, H.CD0, H.K)))


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.9))
    for f, c in CASES:
        V = np.linspace(0.62 * least(f)[0], 68, 300)
        ax.plot(V, np.add(*PF.level_flight_drag(f * H.W, RHO, V, H.S, H.CD0, H.K)), color=c, lw=2.8, label=f"{f * 750:.0f} kg: least drag {least(f)[1]:.0f} N at {least(f)[0]:.1f} m/s")
        v, d = least(f); ax.plot(v, d, "o", color=c, ms=9, zorder=5)
    ax.set_xlim(18, 68); ax.set_ylim(300, 1300); ax.set_xlabel("true airspeed (m/s)"); ax.set_ylabel("drag (N)")
    ax.legend(frameon=False, fontsize=12, loc="upper center")
    despine(ax)
    save(fig, "fig-15-weight-drag")
