#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>

#define BUFFER_SIZE 1024 * 1024  // 1MB buffer size
#define SERVER_PORT 8098
#define FILE_PATH "/home/pq/FeProject/data.txt"

uv_loop_t* loop;
uv_tcp_t server;
FILE* output_file;

void alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
    buf->base = (char*)malloc(suggested_size);
    buf->len = suggested_size;
}

void on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
    if (nread < 0) {
        if (nread != UV_EOF) {
            fprintf(stderr, "Read error: %s\n", uv_strerror(nread));
        }
        fprintf(stdout, "Client disconnected\n");
        uv_close((uv_handle_t*)stream, NULL);
        free(buf->base);
        return;
    }

    if (nread > 0) {
        // Write the received data to the file
        fwrite(buf->base, 1, nread, output_file);
        fflush(output_file);
    }

    free(buf->base);
}

void on_connection(uv_stream_t* server, int status) {
    if (status < 0) {
        fprintf(stderr, "Connection error: %s\n", uv_strerror(status));
        return;
    }

    uv_tcp_t* client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
    uv_tcp_init(loop, client);

    if (uv_accept(server, (uv_stream_t*)client) == 0) {
        fprintf(stdout, "New client connected\n");
        uv_read_start((uv_stream_t*)client, alloc_buffer, on_read);
    } else {
        uv_close((uv_handle_t*)client, NULL);
    }
}

int main1() {
    loop = uv_default_loop();

    // Open the output file
    output_file = fopen(FILE_PATH, "ab");
    if (!output_file) {
        perror("Failed to open output file");
        return 1;
    }

    uv_tcp_init(loop, &server);

    struct sockaddr_in addr;
    uv_ip4_addr("0.0.0.0", SERVER_PORT, &addr);
    uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);

    int r = uv_listen((uv_stream_t*)&server, 128, on_connection);
    if (r) {
        fprintf(stderr, "Listen error: %s\n", uv_strerror(r));
        return 1;
    }

    printf("Server listening on port %d\n", SERVER_PORT);
    uv_run(loop, UV_RUN_DEFAULT);

    uv_loop_close(loop);
    fclose(output_file);

    return 0;
}