"""Lecture 17, Delhi-Mumbai (1139 km): cruise fuel and time of the example's wide-body jet against the along-track wind,
from the inverted Breguet formula with the ground speed (flight.performance), for one way and for the round trip with
the same wind (the second leg's mass is taken equal to the first's at its start). Writes img/fig-17-sector-wind.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import performance as PF
from flight.constants import KT
import _transport as TR

R, V, E, C, M0 = 1139e3, 236.1, 18.9, TR.C, TR.M0
KTS = np.linspace(-60, 60, 121)          # headwind on the way out, kt


def leg(headwind):
    """(cruise fuel in kg, time in s) for one leg flown at constant V and E from mass M0."""
    vg = V - headwind
    unit = PF.range_cruise_climb(vg, E, C, M0, M0 / np.e)      # distance for ln(W0/Wf) = 1
    return M0 * (1 - np.exp(-R / unit)), R / vg


def one_way(kt):
    return leg(kt * KT)


def round_trip(kt):
    (f1, t1), (f2, t2) = leg(kt * KT), leg(-kt * KT)
    return f1 + f2, t1 + t2


if __name__ == "__main__":
    fig, axs = plt.subplots(2, 2, figsize=(10.5, 6.4), sharex=True)
    fig.subplots_adjust(hspace=0.12, wspace=0.28)
    for j, (fn, title, c) in enumerate(((one_way, "Delhi to Mumbai", MAROON), (round_trip, "there and back, same wind", BLUE))):
        d = np.array([fn(k) for k in KTS])
        axs[0, j].plot(KTS, d[:, 0] / 1e3, color=c, lw=2.8); axs[1, j].plot(KTS, d[:, 1] / 60, color=c, lw=2.8)
        axs[0, j].set_title(title, fontsize=12.5)
        for k in (-50, 0, 50):
            f, t = fn(k)
            axs[0, j].plot(k, f / 1e3, "o", color=INK, ms=6)
            axs[0, j].annotate(f"{f / 1e3:.1f} t", (k, f / 1e3), xytext=(-6, 10) if j == 0 else (0 if k == 0 else (10 if k < 0 else -10), 12), textcoords="offset points", ha="right" if j == 0 else ("center" if k == 0 else ("left" if k < 0 else "right")), fontsize=11)
        axs[1, j].set_xlabel("wind on the way out (kt)\nnegative: tailwind")
        for ax in axs[:, j]:
            despine(ax); ax.axvline(0, color=GREY, lw=0.8); ax.set_xlim(-65, 65); ax.margins(y=0.22)
    axs[0, 0].set_ylabel("cruise fuel (t)"); axs[1, 0].set_ylabel("cruise time (min)")
    save(fig, "fig-17-sector-wind")
