"""Lecture 7, three level turns at 100 m/s, seen from above: banks of 30, 45 and 60 deg, all starting at the same
point heading north. Turn rate, radius and load factor from the engine's flight.performance.level_turn.
Writes img/anim-07-turns.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from flight.performance import level_turn

V = 100.0
TURNS = [(np.radians(s), c) for s, c in ((30, GREEN), (45, BLUE), (60, MAROON))]
DATA = [(s, c) + level_turn(V, s) for s, c in TURNS]           # (sigma, colour, rate, radius, n)
T_END = 2 * np.pi / DATA[0][2]                                   # one full circle of the slowest turn

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(9, 8))
    N = 120
    times = np.linspace(0, T_END, N)

    def frame(k):
        ax.clear()
        t = times[k]
        for sig, c, rate, R, n in DATA:
            th = np.linspace(0, min(rate * t, 2 * np.pi), 300)
            x, y = R - R * np.cos(th), R * np.sin(th)             # start at the origin heading north, turning right
            ax.plot(x, y, color=c, lw=2.4)
            ax.plot(x[-1], y[-1], "o", color=c, ms=8)
            if k == N - 1:
                ax.text(R, R + 60, f"{np.degrees(sig):.0f}°: R = {R:.0f} m, {2 * np.pi / rate:.0f} s per circle, n = {n:.2f}",
                        color=c, fontsize=11, ha="center")
        ax.plot(0, 0, "^", color=INK, ms=10)
        ax.text(-80, -260, "start: heading north,\n100 m/s", fontsize=11, ha="right")
        ax.set_xlim(-1900, 3800)
        ax.set_ylim(-2000, 2050)
        ax.set_aspect("equal")
        ax.set_xlabel("east (m)")
        ax.set_ylabel("north (m)")
        ax.text(3700, -1900, f"t = {t:4.0f} s", fontsize=12, ha="right")
        for sp in ("top", "right"):
            ax.spines[sp].set_visible(False)
        return []

    save_anim(fig, frame, N, 15, "anim-07-turns", hold=2.5)
