"""Lecture 4, banking: the aircraft seen from behind, banked from 0 to 60 deg in a level turn. The lift (blue)
must keep its vertical part equal to the weight, so it grows as 1/cos(sigma); its sideways part W tan(sigma)
turns the aircraft. The lift vector is L (cos(sigma) n_gamma + sin(sigma) n_chi) of the note, with n_gamma and
n_chi from the engine (frames.wind_directions) for level flight. Writes img/anim-04-bank.gif."""
import numpy as np
from _visual import plt, save_anim, INK, MAROON, BLUE, PURPLE, AMBER, GREY
from flight.frames import wind_directions
from flight.constants import G0

V = 100.0
SIG = np.radians(np.concatenate([np.linspace(0, 60, 90), np.full(20, 60.0)]))
e_v, n_g, n_c = wind_directions(0.0, 0.0)                      # level, heading north: n_gamma = up, n_chi = east

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(9, 7))
    kw = dict(arrowstyle="-|>", mutation_scale=18, lw=2.6)

    def frame(k):
        ax.clear()
        sig = SIG[k]
        n = 1 / np.cos(sig)
        L = n * (np.cos(sig) * n_g + np.sin(sig) * n_c)         # lift per unit weight, NED components
        Lx, Ly = L[1], -L[2]                                    # screen: right = east, up = -down
        span = 1.3
        w = np.array([np.cos(sig), -np.sin(sig)]) * span / 2    # wing, right wing down for a right bank
        ax.plot([-w[0], w[0]], [-w[1], w[1]], color=INK, lw=6, solid_capstyle="round")
        ax.plot([0], [0], "o", color=INK, ms=16)
        ax.annotate("", xy=(Lx, Ly), xytext=(0, 0), arrowprops=dict(color=BLUE, **kw))
        ax.annotate("", xy=(0, -1.0), xytext=(0, 0), arrowprops=dict(color=PURPLE, **kw))
        ax.annotate("", xy=(0, Ly), xytext=(0, 0), arrowprops=dict(color=BLUE, alpha=0.35, **kw))
        ax.annotate("", xy=(Lx, 0), xytext=(0, 0), arrowprops=dict(color=AMBER, **kw))
        ax.text(Lx + 0.05, Ly, "$L$", color=BLUE, fontsize=16)
        ax.text(0.06, -1.0, "$W$", color=PURPLE, fontsize=16)
        if Lx > 0.15:
            ax.text(Lx / 2 + 0.25, -0.22, "$L\\sin\\sigma$ turns the aircraft", color=AMBER, fontsize=12, ha="center")
        ax.text(-1.95, 1.95, f"bank $\\sigma$ = {np.degrees(sig):4.0f}°", fontsize=14)
        ax.text(-1.95, 1.7, f"load factor $n=1/\\cos\\sigma$ = {n:4.2f}", fontsize=14)
        rate = np.degrees(G0 * np.tan(sig) / V)
        ax.text(-1.95, 1.45, f"turn rate at {V:.0f} m/s = {rate:4.1f} °/s", fontsize=14)
        ax.text(-1.95, -1.35, "seen from behind; the vertical part of the lift always equals the weight", fontsize=11,
                color=GREY)
        ax.set_xlim(-2.0, 2.3)
        ax.set_ylim(-1.45, 2.15)
        ax.set_aspect("equal")
        ax.axis("off")
        return []

    save_anim(fig, frame, len(SIG), 18, "anim-04-bank")
