import pandas as pd
import folium
import numpy as np

# Load the transmitter and receiver log data from CSV files
transmitter_log = pd.read_csv('walk_tx.csv')
receiver_log = pd.read_csv('walk_rx.csv')

# Print the columns to help identify correct column names
print("Transmitter log columns:", transmitter_log.columns)
print("Receiver log columns:", receiver_log.columns)

# Rename columns to match expected format
transmitter_log.rename(columns={
    'sender name': 'sender_name',
    'rx lat': 'rx_lat',
    'rx long': 'rx_long',
    'rx elevation': 'rx_elevation'
}, inplace=True)

receiver_log.rename(columns={
    'sender name': 'sender_name',
    'sender lat': 'sender_lat',
    'sender long': 'sender_long',
    'rx lat': 'rx_lat',
    'rx long': 'rx_long',
    'rx elevation': 'rx_elevation',
    'rx snr': 'rx_snr',
    'hop limit': 'hop_limit'
}, inplace=True)

# Define the expected columns for transmitter and receiver logs
expected_transmitter_columns = ['time', 'from', 'rx_lat', 'rx_long', 'rx_elevation']
expected_receiver_columns = ['time', 'from', 'sender_name', 'sender_lat', 'sender_long', 'rx_lat', 'rx_long', 'rx_elevation', 'rx_snr', 'distance', 'hop_limit', 'payload']

# Check if transmitter log has the expected columns
for col in expected_transmitter_columns:
    if col not in transmitter_log.columns:
        raise KeyError(f"Column '{col}' is missing in transmitter log CSV file.")

# Check if receiver log has the expected columns
for col in expected_receiver_columns:
    if col not in receiver_log.columns:
        raise KeyError(f"Column '{col}' is missing in receiver log CSV file.")

# Calculate map center, ignoring zeros
valid_latitudes = transmitter_log['rx_lat'].replace(0, np.nan).dropna()
valid_longitudes = transmitter_log['rx_long'].replace(0, np.nan).dropna()
map_center = [valid_latitudes.mean(), valid_longitudes.mean()]

# Initialize the map centered at an average location
m = folium.Map(location=map_center, zoom_start=15)

# Plotting transmitter points as blue dots
for _, row in transmitter_log.iterrows():
    if row['rx_lat'] != 0 and row['rx_long'] != 0:
        folium.CircleMarker(
            location=[row['rx_lat'], row['rx_long']],
            radius=5,
            color='blue',
            fill=True,
            fill_color='blue',
            fill_opacity=0.6
        ).add_to(m)

# Plotting receiver points as green circles
for _, row in receiver_log.iterrows():
    if row['sender_lat'] != 0 and row['sender_long'] != 0:
        folium.CircleMarker(
            location=[row['sender_lat'], row['sender_long']],
            radius=8,
            color='green',
            fill=True,
            fill_color='green',
            fill_opacity=0.6
        ).add_to(m)

# Save the map to an HTML file and display
map_file_path = 'transmitter_receiver_map.html'
m.save(map_file_path)
print(f"Map has been saved to {map_file_path}")
