"""Lecture 12: level-flight drag of the HANSA-3-class trainer (fig-12-polar data) against true airspeed (left) and
equivalent airspeed (right) at sea level, 2000 m, and Leh on the 25 deg C day of Lecture 9.
Writes img/fig-12-drag-eas.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from _scripts import load
from flight import performance as PF, atmosphere as A, airspeed as AS
from flight.constants import G0

P = load("fig-12-polar")
W = 750.0 * G0
LEH_DT = 25.0 + 273.15 - A.ISA.standard_tp(3254.0)[0]
CASES = [("sea level", A.isa(0.0)[2], INK, 7.0, "-"), ("2000 m", A.isa(2000.0)[2], BLUE, 4.2, "--"),
         ("Leh, 25 °C", A.at_pressure_altitude(3254.0, LEH_DT)[2], MAROON, 2.0, ":")]
VE = np.linspace(21.0, 70.0, 200)


def drag(rho, V):
    return np.add(*PF.level_flight_drag(W, rho, V, P.S_H, P.CD0_H, P.K_H))


def least(rho):
    v = PF.min_drag_speed(W, rho, P.S_H, P.CD0_H, P.K_H)
    return v, float(drag(rho, v))


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.6), sharey=True, gridspec_kw=dict(wspace=0.08))
    for lab, rho, c, lw, ls in CASES:
        V = AS.tas_from_eas(VE, rho)
        a.plot(V, drag(rho, V), color=c, lw=2.6, label=lab)
        v, d = least(rho); a.plot(v, d, "o", color=c, ms=7)
        b.plot(VE, drag(rho, V), color=c, lw=lw, ls=ls, label=lab)
    a.axhline(least(CASES[0][1])[1], color=GREY, lw=1, ls="--")
    a.text(86, least(CASES[0][1])[1] - 100, f"the same least drag, {least(CASES[0][1])[1]:.0f} N", ha="right", fontsize=11.5)
    a.set_xlabel("true airspeed (m/s)"); b.set_xlabel("equivalent airspeed (m/s)"); a.set_ylabel("drag (N)")
    a.set_xlim(20, 88); b.set_xlim(20, 72); a.set_ylim(350, 1600)
    a.legend(frameon=False, fontsize=11.5, loc="upper center"); b.set_title("three curves on top of each other", fontsize=12)
    despine(a); despine(b)
    save(fig, "fig-12-drag-eas")
