"""Lecture 4, the momentum balance of a rocket: at time t the rocket has mass m and velocity v; at t + dt it has
mass m - dm_e and velocity v + dv, and the gas it threw out, dm_e, moves at v + v_e (v_e points backwards).
Schematic. Writes img/fig-04-momentum.png."""
import numpy as np
from _visual import plt, save, INK, MAROON, BLUE, AMBER, GREY
from matplotlib.patches import Polygon, Circle


def rocket(ax, x, color=MAROON):
    ax.add_patch(Polygon([[x - 0.9, -0.22], [x + 0.6, -0.22], [x + 0.95, 0], [x + 0.6, 0.22], [x - 0.9, 0.22]], color=color))


kw = dict(arrowstyle="-|>", mutation_scale=16, lw=2.2)
if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(2, 1, figsize=(10, 5.4))
    rocket(a1, 0.0)
    a1.text(0.0, 0.0, "$m$", color="white", fontsize=14, ha="center", va="center")
    a1.annotate("", xy=(1.9, 0), xytext=(1.0, 0), arrowprops=dict(color=BLUE, **kw))
    a1.text(1.95, 0, "$\\mathbf{v}$", color=BLUE, fontsize=14, va="center")
    a1.text(-3.3, 0, "time $t$", fontsize=13, va="center")
    rocket(a2, 0.4)
    a2.text(0.4, 0.0, "$m-\\mathrm{d}m_e$", color="white", fontsize=12, ha="center", va="center")
    a2.annotate("", xy=(2.5, 0), xytext=(1.4, 0), arrowprops=dict(color=BLUE, **kw))
    a2.text(2.55, 0, "$\\mathbf{v}+\\mathrm{d}\\mathbf{v}$", color=BLUE, fontsize=14, va="center")
    a2.add_patch(Circle((-1.2, 0), 0.18, color=AMBER))
    a2.text(-1.2, -0.42, "gas $\\mathrm{d}m_e$", color=AMBER, fontsize=12, ha="center")
    a2.annotate("", xy=(-2.1, 0), xytext=(-1.45, 0), arrowprops=dict(color=AMBER, **kw))
    a2.text(-2.2, 0.22, "$\\mathbf{v}+\\mathbf{v}_e$ ($\\mathbf{v}_e$ backwards)", color=AMBER, fontsize=12, ha="center")
    a2.text(-3.3, 0, "time $t+\\mathrm{d}t$", fontsize=13, va="center")
    for a in (a1, a2):
        a.set_xlim(-3.4, 3.6)
        a.set_ylim(-0.85, 0.55)
        a.set_aspect("equal")
        a.axis("off")
    a2.text(-3.3, -0.75, "Newton's law holds for the rocket and its gas together: the same matter at $t$ and at $t+\\mathrm{d}t$.",
            fontsize=11, color=GREY)
    save(fig, "fig-04-momentum")
