"""Lecture 27, the forces that stop Hull's business jet on its landing run at sea level (_takeoff.LAND: flaps 40 deg,
C_L = 0.5173, C_D = 0.07323, brakes mu = 0.35, idle thrust 390 lb, touch-down at 1.2 V_stall), each divided by the
weight, against the airspeed from touch-down to rest: the brake friction mu (W - L), the drag, and the total
decelerating force. Dashed: the same with the lift destroyed (C_L = 0, the drag coefficient unchanged), the effect of
spoilers on the friction alone. Writes img/fig-27-stop-forces.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
import _takeoff as T
from flight import atmosphere as A

RHO = A.isa(0.0)[2]
CFG = T.LAND
V_TD = 1.2 * T.stall(RHO, CFG["clmax"])
V = np.linspace(V_TD, 0.0, 300)
Q = 0.5 * RHO * V**2 * T.S


def forces(cl):
    friction = CFG["mu"] * (T.W - Q * cl) / T.W
    drag = Q * CFG["cd"] / T.W
    idle = CFG["idle"] / T.W
    return friction, drag, friction + drag - idle


F_CLEAN, D_CLEAN, TOT_CLEAN = forces(CFG["cl"])
F_DUMP, _, TOT_DUMP = forces(0.0)
LIFT_SHARE_TD = Q[0] * CFG["cl"] / T.W

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ax.plot(V, F_CLEAN, color=BLUE, lw=2.6, label="brake friction, $\\mu(W-L)/W$")
    ax.plot(V, D_CLEAN, color=MAROON, lw=2.6, label="drag, $D/W$")
    ax.plot(V, TOT_CLEAN, color=INK, lw=3.0, label="total decelerating force / $W$")
    ax.plot(V, F_DUMP, color=BLUE, lw=2.0, ls="--", label="friction with the lift destroyed")
    ax.plot(V, TOT_DUMP, color=INK, lw=2.0, ls="--", label="total with the lift destroyed")
    ax.set_xlim(V_TD * 1.02, 0); ax.set_ylim(0, 0.45)
    ax.set_xlabel("airspeed (m/s), falling during the run $\\rightarrow$"); ax.set_ylabel("force / weight")
    ax.legend(frameon=False, fontsize=11, loc="lower right", bbox_to_anchor=(1.0, 0.06))
    despine(ax)
    save(fig, "fig-27-stop-forces")
