import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Read CAESES data
df = pd.read_csv("track.csv")
df.columns = df.columns.str.strip()
x, y, s, c = [df[k].to_numpy() for k in ("x", "y", "s", "c")]

# Calculate Speed, Ride Time and G-Force
g = 9.80665
v = np.sqrt(np.maximum(2 * g * (y[0] - y), 0))
vreq = np.sqrt(np.maximum(g * (2.1)**2 / (2.1), 0))
vtop = np.sqrt(np.maximum(2 * g * (y[0] - 4.2), 0))
ds = np.diff(s)
v_avg = (v[:-1] + v[1:]) / 2
dt = ds / v_avg
ride_time = np.sum(dt)
g_force = v**2 * np.abs(c) / g

# Write Results to File
with open("results.txt", "w") as file:
    file.write(f"Track_length: {s[-1]:.6f} m\n")
    file.write(f"Ride_time: {ride_time:.6f} s\n")
    file.write(f"Mean_speed: {s[-1] / ride_time:.6f} m/s\n")
    file.write(f"Maximum_speed: {np.max(v):.6f} m/s\n")
    file.write(f"Req_speed: {vreq:.6f} m/s\n")
    file.write(f"Top_speed: {vtop:.6f} m/s\n")
    file.write(f"Maximum_Normal_G-Force: {np.max(g_force):.6f} g")

# Create Animation
if 0:
    fps = 30
    time = np.r_[0, np.cumsum(dt)]
    t = np.arange(0, time[-1], 1/fps)

    xa, ya, sa, va, ga = [np.interp(t, time, a) for a in (x, y, s, v, g_force)]

    fig, ax = plt.subplots(figsize=(8, 5))
    ax.plot(x, y)
    cart, = ax.plot([], [], "o")
    text = ax.text(0.98, 0.95, "", transform=ax.transAxes, ha="right", va="top")

    ax.set(xlabel="x [m]", ylabel="y [m]", title="Roller Coaster")
    ax.axis("equal")
    ax.grid()

    def update(i):
        cart.set_data([xa[i]], [ya[i]])
        text.set_text(f"Time: {t[i]:.2f} s\nDistance: {sa[i]:.2f} m\nSpeed: {va[i]:.2f} m/s\nNormal G-force: {ga[i]:.2f} g")
        return cart, text

    ani = FuncAnimation(fig, update, len(t), interval=1000/fps)
    ani.save("roller_coaster.gif", writer="pillow", fps=fps)
    plt.show()
