#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/select.h>

#define PORT 9090
#define LOW_WATER 10  // user-space SO_SNDLOWAT emulation

int main() {
    int sock;
    struct sockaddr_in serv_addr;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) { perror("socket"); exit(1); }

    // Set non-blocking
    int flags = fcntl(sock, F_GETFL, 0);
    fcntl(sock, F_SETFL, flags | O_NONBLOCK);

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    inet_pton(AF_INET, "192.168.2.1", &serv_addr.sin_addr);

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        if (errno != EINPROGRESS) { perror("connect"); exit(1); }
    }

    printf("[Client] Connected (non-blocking)\n");

    char *msg1 = "Hi";           // 2 bytes (should NOT be sent)
    char *msg2 = "HELLO_WORLD";  // 11 bytes (should be sent)

    // --- Skip small message ---
    if (strlen(msg1) >= LOW_WATER) {
        int sent = send(sock, msg1, strlen(msg1), 0);
        if (sent < 0) perror("[Client] send msg1");
        else printf("[Client] Sent %d bytes: %s\n", sent, msg1);
    } else {
        printf("[Client] Skipping send for small message (%ld bytes < %d)\n",
               strlen(msg1), LOW_WATER);
    }

    // --- Wait until socket is writable for big message ---
    fd_set wfds;
    FD_ZERO(&wfds);
    FD_SET(sock, &wfds);

    if (select(sock + 1, NULL, &wfds, NULL, NULL) > 0) {
        if (FD_ISSET(sock, &wfds)) {
            if (strlen(msg2) >= LOW_WATER) {
                int sent = send(sock, msg2, strlen(msg2), 0);
                if (sent < 0) perror("[Client] send msg2");
                else printf("[Client] Sent %d bytes: %s\n", sent, msg2);
            }
        }
    }

    close(sock);
    return 0;
}

