// This program has been developed by students from the bachelor Computer Science at Utrecht
// University within the Software Project course.
// © Copyright Utrecht University (Department of Information and Computing Sciences)
import { useEffect, useState } from 'react'
import { API_BASE_URL } from '../../config/api.ts';

/**
 * Displays the current connection status of a robot in real time.
 *
 * Opens an SSE connection to the backend (`/robot/ping_stream`) that emits
 * simple boolean JSON messages (`true` or `false`). Updates automatically when
 * the robot connects or disconnects.
 *
 * @returns A React element showing the current robot connection status.
 */
export default function ConnectedRobots() {
  
  /**
   * The current connection state:
   * - `true`: Robot is connected.
   * - `false`: Robot is not connected.
   * - `null`: Connection status is unknown (initial check in progress).
   */
  const [connected, setConnected] = useState<boolean | null>(null);

  useEffect(() => {
    // Open a Server-Sent Events (SSE) connection to receive live ping updates.
    // We're expecting a stream of data like that looks like this: `data = False` or `data = True`
    const eventSource = new EventSource(`${API_BASE_URL}/robot/ping_stream`);
    eventSource.onmessage = (event) => {
    
      // Expecting messages in JSON format: `true` or `false`
      console.log("received message:", event.data);
      try {
        const data = JSON.parse(event.data);

        try {
          setConnected(data)
        }
        catch {
          console.log("couldnt extract connected from incoming ping data")
        }

      } catch {
        console.log("Ping message not in correct format:", event.data);
      }
    };

    // Clean up the SSE connection when the component unmounts.
    return () => eventSource.close();
  }, []);

  return (
    <div>
      <h1>Is robot currently connected?</h1>
      <div>
        <h2>Robot is currently: {connected == null ? "checking..." : (connected ? "connected! 🟢" : "not connected... 🔴")} </h2>
        <h3>
          {connected == null ? "If checking continues, make sure CB is properly loaded with robot at least once." : ""}
        </h3>
      </div>
    </div>
  );
}
