#include "csapp.h"

#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/types.h>

/* Start Helper Routines */

// Takes in a FORWARD message and parses the destination host/port.
// DISCLAIMER: Do NOT use this for proxylab. Parsing for proxy should be done via the http parsing library.
void parse_line(char *line, char *host, char *port) {
    sscanf(line, "FORWARD %99[^:]:%9s\n", host, port);
    return;
}

/* End Helper Routines */

// TODO 1: Generate a safe port number using ./port-for-user.pl
// My Port Number: <insert port # here>

int main(int argc, char **argv) {
    // TODO 2: Open a listening file descriptor to the specified port!
    // Note that we specify the port via a command line argument

    // TODO 3: Wait until a client connects to the port and accept the connection
    int outputfd = STDOUT_FILENO;
    bool forwarding_state = false;

    // TODO 4: Using the RIO library (CSAPP), initialize a RIO object with the connected fd.
    rio_t rio;

    // Now we continually loop to recieve all incoming messages.
    do {
        // TODO 5: Read any incoming message from the connected fd.
        char line[MAXLINE];

        if (strncmp(line, "FORWARD", strlen("FORWARD")) == 0 && !forwarding_state)
        {
          // TODO 7: Handle the FORWARD state messages.

        }
        else if (strncmp(line, "STOP", strlen("STOP")) == 0){
          // TODO 8: Handle the STOP state messages.

        }
        else {
          // TODO 6: Handle general messages.

        }

    } while (1);

    // TODO 9: Close the open file descriptors.

    return 0;
}
