"""Lecture 6, the Earth's rotation moves the impact point: the representative SRBM of the vehicle file, fired
north from Sriharikota (vertical rise 4 s, 30 deg pitch-over), flown on the course simulator with the full model
and with the Coriolis and centrifugal terms switched off. Ground tracks in km east and north of the launch site.
Writes img/anim-06-srbm.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREY, INK
from flight import vehicle, guidance, simulate, eom, frames
from flight.constants import A_EARTH as R

SRBM = vehicle.load("srbm-representative")
INIT = dict(lat_deg=13.7, lon_deg=80.2, h=0.0, V=0.0, gamma_deg=90.0, chi_deg=0.0)
LAW = guidance.GravityTurn(4.0, 30.0, 8.0, 0.0)
ROT = simulate.simulate(SRBM, INIT, LAW, eom.Options(heading_at_rest=0.0), t_end=2000, max_step=0.5)
NOROT = simulate.simulate(SRBM, INIT, LAW, eom.Options(coriolis=False, centrifugal=False, heading_at_rest=0.0), t_end=2000,
                          max_step=0.5)
MISS = frames.great_circle_distance(ROT.lat[-1], ROT.lon[-1], NOROT.lat[-1], NOROT.lon[-1])


def en(tr):
    lat0, lon0 = tr.lat[0], tr.lon[0]
    return (tr.lon - lon0) * R * np.cos(lat0) / 1e3, (tr.lat - lat0) * R / 1e3


if __name__ == "__main__":
    fig, (ax, ah) = plt.subplots(1, 2, figsize=(10.5, 5.4), gridspec_kw=dict(width_ratios=[1, 1.4]))
    N = 110
    T = max(ROT.t[-1], NOROT.t[-1])
    times = np.linspace(0, T, N)
    (e1, n1), (e0, n0) = en(ROT), en(NOROT)

    def frame(k):
        for a in (ax, ah):
            a.clear()
        t = times[k]
        for tr, e, n, c, lab in ((NOROT, e0, n0, GREY, "rotation off"), (ROT, e1, n1, MAROON, "rotation on")):
            m = tr.t <= t
            ax.plot(e[m], n[m], color=c, lw=2.2, label=lab)
            ax.plot(e[m][-1], n[m][-1], "o", color=c, ms=7)
            ah.plot(n[m], tr.h[m] / 1e3, color=c, lw=2.2)
        ax.set_xlim(-30, 10)
        ax.set_ylim(-20, 800)
        ax.set_xlabel("east (km)")
        ax.set_ylabel("north (km)")
        ax.legend(fontsize=11, frameon=False, loc="lower left")
        ah.set_xlim(-20, 800)
        ah.set_ylim(0, 400)
        ah.set_xlabel("north (km)")
        ah.set_ylabel("altitude (km)")
        if k == N - 1:
            ax.annotate(f"{MISS / 1e3:.1f} km\nto the west", (e1[-1], n1[-1]), xytext=(-25, -70), textcoords="offset points",
                        fontsize=11, color=MAROON, ha="center", arrowprops=dict(arrowstyle="->", color=MAROON))
        ah.text(780, 380, f"t = {t:4.0f} s", fontsize=11, ha="right")
        for a in (ax, ah):
            despine(a)
        return []

    save_anim(fig, frame, N, 15, "anim-06-srbm", hold=2.5)
