// module websocket
const WebSocket = require('ws');

module.exports = (server) => {
  const wss = new WebSocket.Server({ server }); // Create WebSocket server
  let clients = {};
  let controller = null;

  // Handle WebSocket connection
  wss.on('connection', (ws) => {
    const socketId = generateSocketId(); // You can create a custom socket ID for identification
    console.log('Client connected: ' + socketId);
    
    // Store client with its WebSocket
    clients[socketId] = { id: socketId, ws: ws };

    // Handle message events from clients
    ws.on('message', (data) => {
      data = JSON.parse(data); // Assuming the message is JSON string

      // Authentication message from client
      if (data.type === 'authenticate') {
        console.log(data);
        if (data.role === 'controller') {
          controller = socketId;
        }
      }

      // Bike up event
      if (data.type === 'bike_up') {
        if (controller) {
          broadcast(data); // Broadcast to all clients
        } else {
          ws.send(JSON.stringify({ type: 'message', message: 'controller is disconnected' }));
        }
      }

      // Bike down event
      if (data.type === 'bike_down') {
        if (controller) {
          broadcast(data); // Broadcast to all clients
        } else {
          ws.send(JSON.stringify({ type: 'message', message: 'controller is disconnected' }));
        }
      }

      // Car up event
      if (data.type === 'car_up') {
        if (controller) {
          broadcast(data); // Broadcast to all clients
        } else {
          ws.send(JSON.stringify({ type: 'message', message: 'controller is disconnected' }));
        }
      }

      // Car down event
      if (data.type === 'car_down') {
        if (controller) {
          broadcast(data); // Broadcast to all clients
        } else {
          ws.send(JSON.stringify({ type: 'message', message: 'controller is disconnected' }));
        }
      }
    });

    // Handle WebSocket close event
    ws.on('close', () => {
      console.log('Client disconnected: ' + socketId);
      if (socketId === controller) {
        controller = null; // Reset controller if it disconnects
      }
      delete clients[socketId]; // Remove client from the list
    });
  });

  // Function to broadcast messages to all clients
  function broadcast(data) {
    for (const socketId in clients) {
      if (clients[socketId] && clients[socketId].ws.readyState === WebSocket.OPEN) {
        clients[socketId].ws.send(JSON.stringify({ type: 'callback', data: data }));
      }
    }
  }

  // Generate a unique socket ID (you can customize this)
  function generateSocketId() {
    return 'client_' + Math.random().toString(36).substr(2, 9);
  }
};