"""Lecture 30: ground tracks of the reference PSLV mission flown from Sriharikota at launch headings 75, 90 and 105 deg,
from lift-off to the cutoff of PS4, on the SFM coastline map. Writes img/anim-30-tracks.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, AMBER, INK
from _gt import draw_map
import _orbit30 as O

CASES = []
for az, c in zip(O.HEADINGS_FULL, (BLUE, GREEN, MAROON)):
    tr = O.full(az)["tr"]
    CASES.append(dict(az=az, c=c, t=tr.t, lat=np.degrees(tr.lat), lon=np.degrees(tr.lon), full=O.full(az)))
T_END = max(c["t"][-1] for c in CASES)
N = 90

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    draw_map(ax, 74, 128, -6, 24, grid=10)
    ax.set_xticks(range(80, 130, 10)); ax.set_yticks(range(0, 25, 10))
    ax.plot(CASES[0]["lon"][0], CASES[0]["lat"][0], "*", color=AMBER, mec=INK, ms=14, zorder=9)
    lines, dots = [], []
    for cs in CASES:
        lines.append(ax.plot([], [], color=cs["c"], lw=2.4, zorder=5, label=f"heading {cs['az']:.0f}°, i = {cs['full']['inc']:.1f}°")[0])
        dots.append(ax.plot([], [], "o", color=cs["c"], ms=7, zorder=6)[0])
    ax.legend(handles=lines, frameon=True, facecolor="white", edgecolor="none", fontsize=10, loc="lower left")
    clock = ax.text(0.98, 0.96, "", transform=ax.transAxes, ha="right", va="top", fontsize=11, zorder=7)
    fig.subplots_adjust(left=0.08, right=0.98, bottom=0.12, top=0.98)

    def frame(k):
        now = T_END * k / (N - 1)
        for cs, ln, dt in zip(CASES, lines, dots):
            m = cs["t"] <= now + 1e-9
            ln.set_data(cs["lon"][m], cs["lat"][m])
            dt.set_data([cs["lon"][m][-1]], [cs["lat"][m][-1]])
        clock.set_text(f"t = {now:.0f} s")
    save_anim(fig, frame, N, 15, "anim-30-tracks")
