#include "seobeo/seobeo.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void Echo_Handler(Seobeo_WebSocket_Server_Connection *p_conn, Seobeo_WebSocket_Message *p_msg, void *p_user_data)
{
  (void)p_user_data;

  if (p_msg->opcode == SEOBEO_WS_OPCODE_TEXT)
  {
    printf("[Echo] Received text: %.*s\n", (int)p_msg->length, (char*)p_msg->data);
    Seobeo_WebSocket_Server_Send_Text(p_conn, (char*)p_msg->data);
  }
  else if (p_msg->opcode == SEOBEO_WS_OPCODE_BINARY)
  {
    printf("[Echo] Received %zu bytes of binary data\n", p_msg->length);
    Seobeo_WebSocket_Server_Send_Binary(p_conn, p_msg->data, p_msg->length);
  }
}

void Chat_Handler(Seobeo_WebSocket_Server_Connection *p_conn, Seobeo_WebSocket_Message *p_msg, void *p_user_data)
{
  (void)p_user_data;

  if (p_msg->opcode == SEOBEO_WS_OPCODE_TEXT)
  {
    char message[2048];
    snprintf(message, sizeof(message), "[%s]: %.*s", p_conn->client_id, (int)p_msg->length, (char*)p_msg->data);

    printf("[Chat] Broadcasting: %s\n", message);
    Seobeo_WebSocket_Server_Broadcast_Text(message, p_conn);
  }
}

void Binary_Handler(Seobeo_WebSocket_Server_Connection *p_conn, Seobeo_WebSocket_Message *p_msg, void *p_user_data)
{
  (void)p_user_data;
  (void)p_conn;

  if (p_msg->opcode == SEOBEO_WS_OPCODE_BINARY)
  {
    printf("[Binary] Received %zu bytes, broadcasting to all clients\n", p_msg->length);
    Seobeo_WebSocket_Server_Broadcast_Binary(p_msg->data, p_msg->length);
  }
}

int main()
{
  printf("=== Seobeo WebSocket Server Example ===\n\n");

  Seobeo_WebSocket_Server_Init();

  Seobeo_WebSocket_Server_Register("/echo", Echo_Handler, NULL);
  printf("Registered /echo endpoint\n");

  Seobeo_WebSocket_Server_Register("/chat", Chat_Handler, NULL);
  printf("Registered /chat endpoint\n");

  Seobeo_WebSocket_Server_Register("/binary", Binary_Handler, NULL);
  printf("Registered /binary endpoint\n");

  printf("\nStarting server on port 8080...\n");
  printf("\nTest with:\n");
  printf("  ws://localhost:8080/echo   - Echo server\n");
  printf("  ws://localhost:8080/chat   - Chat room\n");
  printf("  ws://localhost:8080/binary - Binary data broadcast\n");
  printf("\n");

  Seobeo_Web_Server_Start(NULL, "8080", SEOBEO_MODE_FORK, 0);

  return 0;
}
