/* =============================================================================
 * echoclient.c -- the client half: connect, send lines, read them back
 * =============================================================================
 *
 * [Idea]
 *   A client is even simpler than a server: get a connected descriptor, then
 *   read and write it. The only subtlety is that establishing the connection
 *   may need several attempts -- across the several addresses a name resolves
 *   to (handled inside open_clientfd), and in time, if the server has not
 *   finished starting up (handled here with a short retry loop).
 *
 * [What it answers]
 *   - What does a client do, minimally?
 *   - Why retry, and why walk the address list?
 *   - How does closing the connection signal "I am done" to the server?
 *
 * Usage:   ./echoclient [host] [port]      defaults: localhost 15213
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "netutil.h"
#include "rio.h"

#define MAXLINE 8192

/* The lines this client sends. Fixed, so the demo's output is deterministic. */
static const char *messages[] = {
    "hello, sockets\n",
    "a socket is just a descriptor\n",
    "15213\n",
};
#define NMESSAGES ((int)(sizeof(messages) / sizeof(messages[0])))

int main(int argc, char **argv)
{
    const char *host = (argc > 1) ? argv[1] : "localhost";
    const char *port = (argc > 2) ? argv[2] : "15213";

    /* 1. Connect, retrying briefly: in the scripted demo the server may still
     *    be starting. A real client does the same thing for transient failures.
     *    (open_clientfd already tries every address the name resolves to.) */
    int clientfd = -1;
    for (int attempt = 1; attempt <= 20; attempt++) {
        clientfd = open_clientfd(host, port);
        if (clientfd >= 0)
            break;
        usleep(50 * 1000);      /* 50 ms, up to 20 times = 1 s of patience */
    }
    if (clientfd < 0) {
        fprintf(stderr, "echoclient: cannot connect to %s:%s\n", host, port);
        return 1;
    }
    printf("[client] connected to %s:%s (clientfd=%d)\n", host, port, clientfd);

    /* 2. Talk. Write a line, read the echo. Note we read with RIO because the
     *    reply may arrive in pieces -- a socket short-counts freely (L18). */
    rio_t rio;
    rio_readinitb(&rio, clientfd);

    char buf[MAXLINE];
    char sent[128];
    for (int i = 0; i < NMESSAGES; i++) {
        size_t len = strlen(messages[i]);

        /* Send the line (including its '\n', which is what makes it a line). */
        if (rio_writen(clientfd, messages[i], len) != (ssize_t)len) {
            perror("rio_writen");
            break;
        }

        /* Read the echoed line back. */
        ssize_t n = rio_readlineb(&rio, buf, MAXLINE);
        if (n <= 0) {
            printf("[client] server closed the connection early\n");
            break;
        }
        buf[n] = '\0';

        /* Trim the trailing newline from both strings, only for tidy printing.
           `sent` is built WITH its quotes so one %-34s aligns the column. */
        if (n > 0 && buf[n - 1] == '\n')
            buf[n - 1] = '\0';
        snprintf(sent, sizeof(sent), "\"%.*s\"", (int)len - 1, messages[i]);

        printf("[client] sent %-34s got back \"%s\"\n", sent, buf);
    }

    /* 3. close() sends EOF to the server, which is how it learns we are done.
     *    Forgetting this is why a server sometimes seems to hang forever. */
    close(clientfd);
    printf("[client] closed the connection (the server now sees EOF)\n");

    printf("\nObservations (client side)\n--------------------------\n");
    printf("- the client needed only open_clientfd + rio_writen/rio_readlineb:\n");
    printf("  after connect(), a socket is read and written like any file.\n");
    printf("- every line came back byte-for-byte: TCP delivered an ordered,\n");
    printf("  reliable byte STREAM, not packets we had to reassemble.\n");
    printf("- close() is a message too: it gives the server EOF so it knows the\n");
    printf("  conversation ended.\n");
    return 0;
}
