"""Lecture 3, how the north-east-down frame turns as a vehicle moves over the sphere (flight.frames.ned_basis).
Left: flying due north from Sriharikota along a meridian, seen from the side. North and down tilt together, about the
west axis, as the latitude grows (the -phi-dot e_E part of eq-Omega). Right: flying due east at 60 deg N, seen from
above the North Pole. North always points towards the pole, so seen from above the north arrow swings through the
full change in longitude. Only sin(60 deg) of that is a turn about the local vertical (the -lambda-dot sin(phi) e_D part);
the rest tilts the horizon about the north axis (lambda-dot cos(phi) e_N). Earlier positions stay drawn, faded. Writes img/anim-03-ned-turning.gif."""
import numpy as np
from matplotlib.patches import Circle
from _visual import plt, save_anim, MAROON, BLUE, INK, GREY
from flight.frames import ned_basis

LATS = np.radians(np.linspace(13.72, 76.0, 73))             # left panel, longitude 0
LAT_E = np.radians(60.0)
LONS = np.radians(np.linspace(0.0, 150.0, 73))              # right panel
N = len(LATS)


def north_turn_rate(lat, lon, h=1e-6):
    """Rate of turn of e_N about the local vertical, per radian of longitude: d(e_N)/d(lambda) . e_E."""
    dn = (ned_basis(lat, lon + h)[0] - ned_basis(lat, lon - h)[0]) / (2 * h)
    return float(dn @ ned_basis(lat, lon)[1])


RATE_60, RATE_0 = north_turn_rate(LAT_E, 0.3), north_turn_rate(0.0, 0.3)
TURN_TOTAL = np.degrees(abs(RATE_60) * (LONS[-1] - LONS[0]))
KEEP = range(0, N, 18)


def arrow(ax, p, d, c, alpha=1.0):
    ax.annotate("", xy=p + d, xytext=p, arrowprops=dict(arrowstyle="-|>", color=c, lw=2.4, mutation_scale=15, alpha=alpha,
                                                        shrinkA=0, shrinkB=0), zorder=5)


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 5.4))
    fig.subplots_adjust(wspace=0.06, left=0.02, right=0.98)

    def draw_north(k, alpha):
        e_n, _, e_d = ned_basis(LATS[k], 0.0)
        r = -e_d
        p = np.array([r[0], r[2]])                           # the meridian plane is x-z
        arrow(a, p, 0.34 * np.array([e_n[0], e_n[2]]), MAROON, alpha)
        arrow(a, p, 0.34 * np.array([e_d[0], e_d[2]]), BLUE, alpha)
        a.plot(*p, "o", color=INK, ms=6, alpha=alpha, zorder=6)

    def draw_east(k, alpha):
        e_n, e_e, e_d = ned_basis(LAT_E, LONS[k])
        p = -e_d[:2]                                         # view from above: x right, y up
        arrow(b, p, 0.34 * e_n[:2] / np.linalg.norm(e_n[:2]), MAROON, alpha)
        arrow(b, p, 0.34 * e_e[:2], INK, alpha)
        b.plot(*p, "o", color=INK, ms=6, alpha=alpha, zorder=6)

    def frame(k):
        a.clear(); b.clear()
        th = np.linspace(0, np.pi / 2, 100)
        a.plot(np.cos(th), np.sin(th), color=GREY, lw=2)
        a.plot([0, 1.15], [0, 0], color=GREY, lw=1); a.plot([0, 0], [0, 1.45], color=GREY, lw=1, ls="--")
        a.text(0.02, 1.43, "Earth's axis", fontsize=11, color=GREY, va="top")
        a.text(1.12, -0.07, "equator", fontsize=11, color=GREY, ha="right")
        full = np.linspace(0, 2 * np.pi, 200)
        for rr, ls in ((1.0, "-"), (np.cos(LAT_E), "--")):
            b.plot(rr * np.cos(full), rr * np.sin(full), color=GREY, lw=1.6, ls=ls)
        b.plot(0, 0, "+", color=INK, ms=12); b.text(0.0, -0.22, "North Pole", fontsize=11, ha="center")
        b.text(-0.72, -0.78, "equator", fontsize=11, color=GREY)
        for j in KEEP:
            if j < k:
                draw_north(j, 0.35); draw_east(j, 0.35)
        draw_north(k, 1.0); draw_east(k, 1.0)
        a.set_title(f"flying north: latitude {np.degrees(LATS[k]):.0f}°", fontsize=12)
        turned = np.degrees(abs(RATE_60) * (LONS[k] - LONS[0]))
        b.set_title(f"flying east at 60° N: longitude +{np.degrees(LONS[k]):.0f}°", fontsize=12)
        a.text(0.55, -0.22, "north (maroon) and\ndown (blue) tilt", fontsize=11.5, ha="center", va="top")
        b.text(0.0, -1.2, f"from above, north has swung {np.degrees(LONS[k]):.0f}°;\nabout the local vertical, {turned:.0f}°", fontsize=11.5, ha="center", va="top")
        a.set_xlim(-0.25, 1.45); a.set_ylim(-0.5, 1.52); a.set_aspect("equal"); a.axis("off")
        b.set_xlim(-1.3, 1.3); b.set_ylim(-1.6, 1.15); b.set_aspect("equal"); b.axis("off")
        return []

    save_anim(fig, frame, N, 15, "anim-03-ned-turning", dpi=90, hold=3.0)
