"""Lecture 24: a level turn and a 60 deg descending spiral at the same speed (150 m/s) and load factor 3, flown for the
same time (flight.performance.climbing_turn). Left: the paths. Right: the angle turned through by the heading and by
the velocity vector. Writes img/anim-24-helix.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, INK, GREY
from flight import performance as PF

V, N, GAM = 150.0, 3.0, np.radians(-60.0)
LEVEL = PF.climbing_turn(V, N, 0.0)
SPIRAL = PF.climbing_turn(V, N, GAM)
T_END = 2 * np.pi / LEVEL[0]                    # one full level turn


def path(rate, R, gam, t):
    return R * np.sin(rate * t), R * (1 - np.cos(rate * t)), V * np.sin(gam) * t


if __name__ == "__main__":
    fig = plt.figure(figsize=(10.5, 4.9))
    a = fig.add_axes([0.0, 0.02, 0.5, 0.96], projection="3d"); b = fig.add_axes([0.6, 0.14, 0.38, 0.8])
    times = np.linspace(0, T_END, 60)

    def frame(k):
        a.clear(); b.clear(); a.set_facecolor("none")
        t = np.linspace(0, times[k], 300)
        for (rate, R, vrate), g, c, lab in ((LEVEL, 0.0, BLUE, "level turn"), (SPIRAL, GAM, MAROON, "60° spiral")):
            x, y, z = path(rate, R, g, t)
            a.plot(x, y, z, color=c, lw=2.6, label=lab)
            d = np.array([np.cos(g) * np.cos(rate * t[-1]), np.cos(g) * np.sin(rate * t[-1]), np.sin(g)]) * 260
            a.quiver(x[-1], y[-1], z[-1], *d, color=c, lw=2, arrow_length_ratio=0.25)
            b.plot(t, np.degrees(rate * t), color=c, lw=2.6, label=f"{lab}: heading")
            b.plot(t, np.degrees(vrate * t), color=c, lw=2.2, ls="--", label=f"{lab}: velocity vector")
        a.set_xlim(-900, 900); a.set_ylim(-300, 1500); a.set_zlim(-V * np.sin(-GAM) * T_END, 100)
        a.set_xlabel("m"); a.set_ylabel("m"); a.set_zlabel("height (m)"); a.view_init(18, -62)
        a.tick_params(labelsize=8); a.legend(frameon=False, fontsize=10.5, loc="upper left")
        b.set_xlim(0, T_END); b.set_ylim(0, np.degrees(SPIRAL[0] * T_END) * 1.05)
        b.set_xlabel("time (s)"); b.set_ylabel("angle turned through (deg)")
        b.legend(frameon=False, fontsize=10, loc="upper left")
        b.spines["top"].set_visible(False); b.spines["right"].set_visible(False)
        return []

    save_anim(fig, frame, len(times), 10, "anim-24-helix", dpi=90, hold=2.5)
