/*
 * Copyright 2012 Steven Gribble
 *
 *  This file is part of the UW CSE 333 lecture code (333lec).
 *
 *  333lec is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  333lec is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with 333proj.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>

#include "HttpServer.h"

void HandleFunction(int client_fd,
                    std::string requested_URL,
                    std::string client_IP,
                    unsigned short client_port) {
  std::cout << "In handlefunction, URL '"
            << requested_URL << "', IP "
            << client_IP << ", port "
            << client_port << std::endl;

  // Write our response.
  FILE *f = fdopen(client_fd, "w+");
  if (f == NULL) {
    return;
  }

  std::stringstream ss;
  ss << "HTTP/1.1 200 OK\r\n"
     << "Content-type: text/html\r\n"
     << "\r\n"
     << "<html><body>\n"
     << "Hello, " << client_IP << ":" << client_port << "!<p>\n"
     << "You asked for:\n"
     << "<blockquote>\n"
     << "  " << requested_URL << "\n"
     << "</blockquote>\n"
     << "</body></html>\n";
  fwrite(ss.str().c_str(), ss.str().size(), 1, f);
  fclose(f);
}

int main(int argc, char **argv) {
  HttpServer hs(argv[1]);
  hs.AcceptDispatch(&HandleFunction);
  return EXIT_SUCCESS;
}