#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "process.h"
#include "lxcstat.h"

volatile sig_atomic_t stop_server = 0;

void handle_signal(int signal) {
    stop_server = 1; // Set the flag to stop the server
}

void *self_connector_thread(void *arg) {
  int port = *((int *) arg);

  while (!stop_server) {
    sleep(3);  // Wait for the stop signal
  }

  // Connect to the server's listening port to unblock accept()
  int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
  if (sock_fd < 0) {
    perror("self-connector socket");
    return NULL;
  }

  struct sockaddr_in server_address = {
      .sin_family = AF_INET,
      .sin_port = htons(port),
      .sin_addr.s_addr = htonl(INADDR_LOOPBACK),  // Connect to localhost
  };

  connect(sock_fd, (struct sockaddr *)&server_address, sizeof(server_address));
  sleep(1);
  close(sock_fd);
  return NULL;
}

#define BUFFER_SIZE 1024

void handle_client(int client_socket) {
  char *data = readProcesses("/proc");
  int length = strlen(data);
  printf("Got data of length: %d\n", length);

  // HTTP response
  const char *http_headers_fmt =
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/plain\r\n"
      "Content-Length: %u\r\n"
      "Connection: close\r\n"
      "\r\n";

  char headers[BUFFER_SIZE];
  sprintf(headers, http_headers_fmt, length);

  printf("Sending headers\n");
  if (send(client_socket, headers, strlen(headers), 0) == -1) {
    printf("Failed to send headers\n");
    free(data);
    return;
  } else {
    printf("Sent headers\n");
  }

  // Send the response to the client
  int total_sent = 0;

  while (total_sent < length) {
    int amt = length - total_sent;
    int sent = send(client_socket, data + total_sent, amt, 0);
    printf("Tried sending %d actually sent %d\n", amt, sent);
    if (sent == -1) {
      printf("Failed to complete response\n");
      goto closeConnection;
    }
    total_sent += sent;
  }

closeConnection:
  printf("Closing connection\n");
  // Close the client socket
  usleep(100000);
  close(client_socket);
  free(data);
}

int main(int argc, char *argv[]) {
  if (argc == 1) {
    char *buf = readProcesses("/proc");
    if (buf == NULL) return 1;
    printf(buf);
    free(buf);
    return 0;
  }

  for (int i=0; i<strlen(argv[1]); i++) {
    if (argv[1][i] < '0' || argv[1][i] > '9') {
      fprintf(stderr, "Argument '%s' is not a valid port", argv[1]);
      return 1;
    }
  }
  
  int port = atoi(argv[1]);
  // Set up signal handling
  struct sigaction sa;
  sa.sa_handler = handle_signal;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  if (sigaction(SIGINT, &sa, NULL) == -1 || sigaction(SIGTERM, &sa, NULL) == -1) {
      perror("sigaction");
      exit(EXIT_FAILURE);
  }

  int server_socket, client_socket;
  struct sockaddr_in server_addr, client_addr;
  socklen_t addr_len = sizeof(client_addr);

  // Create the server socket
  if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Socket creation failed");
    exit(EXIT_FAILURE);
  }

  // Configure the server address
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = INADDR_ANY;
  server_addr.sin_port = htons(port);

  // Bind the socket to the specified port
  if (bind(server_socket, (struct sockaddr *)&server_addr,
           sizeof(server_addr)) == -1) {
    perror("Bind failed");
    close(server_socket);
    exit(EXIT_FAILURE);
  }

  // Listen for incoming connections
  if (listen(server_socket, 5) == -1) {
    perror("Listen failed");
    close(server_socket);
    exit(EXIT_FAILURE);
  }

  // Start the self-connector thread
  pthread_t connector_thread;
  pthread_create(&connector_thread, NULL, self_connector_thread, (void *) &port);

  printf("Server is listening on port %d (PID %d)\n", port, getpid());

  // Accept and handle incoming connections
  while (1) {
    client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &addr_len);
    printf("Got client connection\n");
    if (stop_server) break; // stop if we received SIGTERM or SIGINT

    if (client_socket == -1) {
      perror("Accept failed");
      continue;
    }

    // Handle the client in a separate function
    handle_client(client_socket);
  }

  close(client_socket);
  close(server_socket);

  printf("Shutting down\n");
  pthread_join(connector_thread, NULL);
  return 0;
}
