"""Lecture 10, the airspeed indicator of a light trainer that climbs from sea level to 4 km holding 70 kt on the dial.
At these speeds the dial shows the equivalent airspeed (compressibility is negligible), so the needle and the stall
mark do not move, while the true airspeed grows as the air thins. HANSA-3 class, the stall speed of
fig-10-stall-speeds.py. Writes img/anim-10-dial.gif."""
import numpy as np
from matplotlib.patches import Wedge, Circle
from _visual import plt, save_anim, MAROON, GREEN, BLUE, INK, GREY, CREAM
from _scripts import load
from flight import atmosphere as A, airspeed as AS
from flight.constants import KT

STALL = load("fig-10-stall-speeds")
VE_KT = 70.0
VS_KT = STALL.VS_EAS[0] / KT
H = np.linspace(0.0, 4000.0, 81)
TAS_KT = np.array([AS.tas_from_eas(VE_KT * KT, A.isa(h)[2]) / KT for h in H])
VMAX = 160.0
A0, A1 = 225.0, -45.0            # dial angles (deg) of 0 and VMAX kt, clockwise


def ang(v):
    return np.radians(A0 + (A1 - A0) * v / VMAX)


def dial(ax, v_needle):
    ax.add_patch(Circle((0, 0), 1.05, facecolor="#2b2723", edgecolor=INK, lw=2))
    ax.add_patch(Wedge((0, 0), 0.98, np.degrees(ang(VMAX)), np.degrees(ang(VS_KT)), width=0.07, color="#e9e2d0"))
    ax.add_patch(Wedge((0, 0), 0.98, np.degrees(ang(VS_KT)) - 0.8, np.degrees(ang(VS_KT)) + 0.8, width=0.14, color=MAROON))
    for v in range(0, int(VMAX) + 1, 10):
        a = ang(v)
        r0 = 0.80 if v % 20 == 0 else 0.86
        ax.plot([r0 * np.cos(a), 0.91 * np.cos(a)], [r0 * np.sin(a), 0.91 * np.sin(a)], color=CREAM, lw=1.6)
        if v % 20 == 0:
            ax.text(0.66 * np.cos(a), 0.66 * np.sin(a), f"{v}", color=CREAM, ha="center", va="center", fontsize=13)
    ax.text(0, -0.42, "KNOTS", color=CREAM, ha="center", fontsize=11)
    a = ang(v_needle)
    ax.plot([-0.12 * np.cos(a), 0.86 * np.cos(a)], [-0.12 * np.sin(a), 0.86 * np.sin(a)], color="#f4f1ea", lw=4, solid_capstyle="round")
    ax.add_patch(Circle((0, 0), 0.06, color="#f4f1ea"))
    ax.set_xlim(-1.15, 1.15); ax.set_ylim(-1.15, 1.15)
    ax.set_aspect("equal"); ax.axis("off")


if __name__ == "__main__":
    fig, (ad, ah) = plt.subplots(1, 2, figsize=(11, 5.6), gridspec_kw=dict(width_ratios=[1, 1.15]))
    fig.subplots_adjust(left=0.03, right=0.97, bottom=0.14, top=0.88, wspace=0.25)
    N = len(H)

    def frame(k):
        ad.clear(); ah.clear()
        dial(ad, VE_KT)
        ad.set_title(f"the dial: {VE_KT:.0f} kt (stall mark {VS_KT:.0f} kt)", fontsize=13)
        ah.plot([VE_KT] * (k + 1), H[:k + 1] / 1e3, color=GREEN, lw=2.6, label="on the dial (EAS)")
        ah.plot(TAS_KT[:k + 1], H[:k + 1] / 1e3, color=MAROON, lw=2.6, label="through the air (TAS)")
        ah.plot(VE_KT, H[k] / 1e3, "o", color=GREEN, ms=7)
        ah.plot(TAS_KT[k], H[k] / 1e3, "o", color=MAROON, ms=7)
        ah.set_xlim(60, 90); ah.set_ylim(0, 4.3)
        ah.set_xlabel("speed (kt)"); ah.set_ylabel("altitude (km)")
        ah.set_title(f"altitude {H[k]:.0f} m   true airspeed {TAS_KT[k]:.1f} kt", fontsize=13, loc="left")
        ah.text(69, 2.2, "on the dial\n(EAS)", ha="right", fontsize=12, color=GREEN)
        ah.text(76, 0.7, "through the air\n(TAS)", fontsize=12, color=MAROON)
        for s in ("top", "right"):
            ah.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 12, "anim-10-dial", hold=2.5)
