#!/bin/python3

# Copyright (c) 2020, University of Padova, Dep. of Information Engineering, SIGNET lab
# Copyright (c) 2025, Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
#
# SPDX-License-Identifier: GPL-2.0-only

import matplotlib.animation as animation
import matplotlib.patches as patches
import matplotlib.pyplot as plt

#
#  Plot the traces generated by three-gpp-v2v-channel-example
#
import pandas as pd

# Load the data
df = pd.read_csv("three-gpp-v2v-channel-example-output.txt", sep=r"\s+", comment="#")
df = df.iloc[::10, :]

# Column indices (adjust if needed)
TIME = 0
TX_X = 1
TX_Y = 2
RX_X = 3
RX_Y = 4
SNR = 6

# Create the figure and subplots
fig, (ax_map, ax_snr) = plt.subplots(1, 2, figsize=(12, 6))

# Map plot config
ax_map.set_xlim(-25, 600)
ax_map.set_ylim(-25, 1000)
ax_map.set_xlabel("X [m]")
ax_map.set_ylabel("Y [m]")
ax_map.set_aspect("equal")
tx_circle = patches.Circle((0, 0), 5, color="blue", alpha=0.35)
rx_circle = patches.Circle((0, 0), 5, color="red", alpha=0.35)
ax_map.add_patch(tx_circle)
ax_map.add_patch(rx_circle)

# SNR plot config
ax_snr.set_xlim(0, 40)
ax_snr.set_ylim(-20, 100)
ax_snr.set_xlabel("Time [s]")
ax_snr.set_ylabel("SNR [dB]")
ax_snr.grid(True)
(snr_line,) = ax_snr.plot([], [], "k-")

buildings = pd.read_csv(
    "three-gpp-v2v-channel-example-buildings.txt", sep=r"\s+", comment="#", header=None
)
building_patches = []
for idx, row in buildings.iterrows():
    x0, y0, x1, y1 = row
    width = x1 - x0
    height = y1 - y0
    rect = patches.Rectangle((x0, y0), width, height, color="gray", alpha=0.5)
    ax_map.add_patch(rect)
    building_patches.append(rect)


# Animation update function
def update(frame):
    row = df.iloc[frame]
    tx_circle.set_center((row.iloc[TX_X], row.iloc[TX_Y]))
    rx_circle.set_center((row.iloc[RX_X], row.iloc[RX_Y]))
    snr_line.set_data(df.iloc[: frame + 1, TIME], df.iloc[: frame + 1, SNR])
    ax_map.set_title(f"Time = {row.iloc[TIME]:.1f} s")
    return tx_circle, rx_circle, snr_line


# Run animation
ani = animation.FuncAnimation(fig, update, frames=len(df), interval=0.001, blit=False)

# Save animation
ani.save("three-gpp-v2v-channel-example-map.gif", writer="pillow")

# Save final SNR plot separately
plt.figure()
plt.plot(df.iloc[:, TIME], df.iloc[:, SNR], "k-")
plt.xlabel("Time [s]")
plt.ylabel("SNR [dB]")
plt.grid(True)
plt.xlim(0, 40)
plt.ylim(-20, 100)
plt.savefig("three-gpp-v2v-channel-example-snr.png")
