import tkinter as tk
from tkinter import ttk
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pywifi
import time

# --------------------------
# Parameters
# --------------------------
N_POINTS_PER_NETWORK = 50   # Dots per network
dt = 50                      # Animation interval in ms
MAX_NETWORKS = 5             # Maximum networks to track
AMPLITUDE_SCALE = 1.0        # Slider-controlled amplitude

# --------------------------
# Tkinter setup
# --------------------------
root = tk.Tk()
root.title("Analog Wi-Fi EMF Visualizer")

# --------------------------
# Sliders
# --------------------------
slider_frame = tk.Frame(root)
slider_frame.pack(side=tk.BOTTOM, fill=tk.X)

ampl_var = tk.DoubleVar(value=AMPLITUDE_SCALE)
tk.Label(slider_frame, text="Amplitude Scale").pack(side=tk.LEFT)
tk.Scale(slider_frame, from_=0.1, to=5, resolution=0.1,
         orient=tk.HORIZONTAL, variable=ampl_var).pack(side=tk.LEFT)

# --------------------------
# Matplotlib figure
# --------------------------
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111, projection='3d')
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

# --------------------------
# Wi-Fi scanning setup
# --------------------------
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]

def get_wifi_signals():
    iface.scan()
    time.sleep(0.2)  # Allow scan to complete
    results = iface.scan_results()
    signals = {}
    for r in results[:MAX_NETWORKS]:
        signals[r.ssid] = r.signal
    return signals

# --------------------------
# Initialize scatter
# --------------------------
colors = plt.cm.hsv(np.linspace(0,1,MAX_NETWORKS))
all_points = N_POINTS_PER_NETWORK * MAX_NETWORKS
positions = np.zeros((all_points, 3))
scatter = ax.scatter(positions[:,0], positions[:,1], positions[:,2],
                     c=np.repeat(colors, N_POINTS_PER_NETWORK, axis=0),
                     s=20)

# --------------------------
# Animation update
# --------------------------
def update(frame):
    signals = get_wifi_signals()
    idx = 0
    for net_idx, (ssid, strength) in enumerate(signals.items()):
        amp = ampl_var.get() * (strength/100.0)
        for i in range(N_POINTS_PER_NETWORK):
            # Random jitter modulated by signal strength
            positions[idx,0] += np.random.uniform(-1,1)*amp*0.1
            positions[idx,1] += np.random.uniform(-1,1)*amp*0.1
            positions[idx,2] += np.random.uniform(-1,1)*amp*0.1
            idx += 1
    scatter._offsets3d = (positions[:,0], positions[:,1], positions[:,2])
    ax.set_xlim(-5,5)
    ax.set_ylim(-5,5)
    ax.set_zlim(-5,5)
    return scatter,

ani = FuncAnimation(fig, update, interval=dt, blit=False)

# --------------------------
# Tkinter loop
# --------------------------
root.mainloop()
