"""Lecture 12, a wing section at increasing angle of attack: lift and drag (drag drawn five times longer), and the lift
curve traced alongside, through the stall. Section shape NACA 2412 (geometry only). Coefficients: the HANSA-3-class
model of fig-12-polar.py with flight.aero.PolarAero: lift slope from Sadraey eq. 2.13 at its aspect ratio, a
zero-lift angle of -2 deg (ASSUMED for a cambered section), C_Lmax 1.5, and the engine's post-stall model.
Writes img/anim-12-alpha.gif."""
import numpy as np
from matplotlib.patches import FancyArrowPatch, Polygon
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load
from flight import aero as AE

P = load("fig-12-polar")
CLA = AE.finite_wing_slope(P.AR_H)
ALPHA0 = np.radians(-2.0)
MODEL = AE.PolarAero(P.S_H, P.CD0_H, P.K_H, CLA, P.CLMAX_H, alpha0=ALPHA0)
ALPHAS = np.radians(np.linspace(-4.0, 22.0, 105))
CLCD = np.array([MODEL.coefficients(a, 0.1) for a in ALPHAS])
A_STALL = np.degrees(ALPHA0 + P.CLMAX_H / CLA)


def naca2412(n=80):
    m, p, t = 0.02, 0.4, 0.12
    x = 0.5 * (1 - np.cos(np.linspace(0, np.pi, n)))
    yt = 5 * t * (0.2969 * np.sqrt(x) - 0.126 * x - 0.3516 * x**2 + 0.2843 * x**3 - 0.1015 * x**4)
    yc = np.where(x < p, m / p**2 * (2 * p * x - x**2), m / (1 - p)**2 * (1 - 2 * p + 2 * p * x - x**2))
    upper = np.c_[x, yc + yt]
    lower = np.c_[x, yc - yt]
    return np.vstack([upper, lower[::-1]])


SHAPE = naca2412() - np.array([0.25, 0.0])

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.0), gridspec_kw=dict(width_ratios=[1.15, 1]))
    fig.subplots_adjust(wspace=0.22, bottom=0.14, top=0.9)

    def frame(k):
        a1.clear(); a2.clear()
        al = ALPHAS[k]
        cl, cd = CLCD[k]
        R = np.array([[np.cos(al), np.sin(al)], [-np.sin(al), np.cos(al)]])
        a1.add_patch(Polygon(SHAPE @ R.T, closed=True, facecolor="#e6e0d2", edgecolor=INK, lw=1.5))
        for y in (-0.35, -0.15, 0.25, 0.45):
            a1.annotate("", (-0.55, y), (-0.95, y), arrowprops=dict(arrowstyle="->", color=GREY, lw=1))
        stalled = np.degrees(al) > A_STALL
        if stalled:
            xs = np.linspace(0.1, 1.1, 60)
            for j in range(3):
                a1.plot(xs, 0.05 + 0.08 * j + 0.03 * np.sin(18 * xs + 2 * j) + 0.12 * (xs - 0.1), color=GREY, lw=1)
            a1.text(0.15, 0.55, "separated flow", color=GREY, fontsize=12)
        a1.add_patch(FancyArrowPatch((0, 0), (0, 0.42 * cl), arrowstyle="-|>", mutation_scale=18, color=BLUE, lw=2.5))
        a1.add_patch(FancyArrowPatch((0, 0), (5 * 0.42 * cd, 0), arrowstyle="-|>", mutation_scale=18, color=MAROON, lw=2.5))
        a1.text(0.04, 0.42 * cl + 0.04, "lift", color=BLUE, fontsize=13)
        a1.text(5 * 0.42 * cd + 0.02, -0.22, "drag ($\\times5$)", color=MAROON, fontsize=12)
        a1.set_xlim(-1.0, 1.1); a1.set_ylim(-0.6, 0.8); a1.set_aspect("equal"); a1.axis("off")
        a1.set_title(f"$\\alpha={np.degrees(al):.1f}^\\circ$", fontsize=14, loc="left")
        a1.text(-0.95, -0.55, f"$C_L={cl:.2f}$   $C_D={cd:.3f}$   $L/D={cl / cd:.1f}$", fontsize=13)
        a2.plot(np.degrees(ALPHAS[:k + 1]), CLCD[:k + 1, 0], color=BLUE, lw=2.5)
        a2.plot(np.degrees(al), cl, "o", color=BLUE, ms=7)
        a2.axvline(A_STALL, color=GREY, ls=":", lw=1)
        a2.text(A_STALL + 0.4, 0.15, "stall", color=GREY, fontsize=12)
        a2.set_xlim(-5, 23); a2.set_ylim(-0.3, 1.7)
        a2.set_xlabel("angle of attack (deg)"); a2.set_ylabel("$C_L$")
        for s in ("top", "right"):
            a2.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(ALPHAS), 12, "anim-12-alpha", dpi=90, hold=2.5)
