// Generated by CoffeeScript 1.6.2
(function() {
  var CSS_URL, VERSION, echoback, express, http, map;

  express = require('express');

  http = require('http');

  map = require('underscore').map;

  VERSION = require('../package.json').version;

  CSS_URL = "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css";

  module.exports = echoback = function(serverName, port, cb) {
    var app, handler, log, requestToHTML, requestToJSON, server, shouldSendJSON;

    app = express();
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    log = function(msg) {
      return console.log(msg);
    };
    requestToJSON = function(req) {
      return JSON.stringify({
        route: "" + req.method + " " + req.path,
        server: serverName,
        port: port,
        path: req.path,
        query: req.query,
        cookies: req.cookies,
        headers: req.headers,
        body: req.body
      });
    };
    requestToHTML = function(req) {
      var body, cookies, headers, query;

      query = map(req.query, function(val, key) {
        return "<li>" + key + ": " + val + "</li>";
      });
      query = query.join('');
      cookies = map(req.cookies, function(val, key) {
        return "<li>" + key + ": " + val + "</li>";
      });
      cookies = cookies.join('');
      headers = map(req.headers, function(val, key) {
        return "<li>" + key + ": " + val + "</li>";
      });
      headers = headers.join('');
      body = Object.keys(req.body).length > 0 ? req.body : "";
      return "<!doctype html>\n<html>\n<head>\n  <title>" + serverName + " | Echoback " + VERSION + "</title>\n  <style>* { font-family: Helvetica, Arial, sans-serif; }</style>\n</head>\n<body>\n  <h1>" + req.method + " " + req.path + "</h1>\n  <h3>Port: " + port + "</h3>\n  <h3>Query:</h3>\n  <ul>" + query + "</ul>\n  <h3>Cookies:</h3>\n  <ul>" + cookies + "</ul>\n  <h3>Headers:</h3>\n  <ul>" + headers + "</ul>\n  <h3>Body:</h3>\n  <div>" + body + "</div>\n</body>\n</html>";
    };
    shouldSendJSON = function(path) {
      return /\.json$/.test(path);
    };
    handler = function(req, res) {
      if (shouldSendJSON(req.path)) {
        res.type('json');
        return res.send(requestToJSON(req));
      } else {
        res.type('html');
        return res.send(requestToHTML(req));
      }
    };
    app.all('*', handler);
    server = http.createServer(app).listen(port, function() {
      log("" + serverName + " now listening on " + port);
      return typeof cb === "function" ? cb() : void 0;
    });
    if (process.env.NODE_ENV === 'test') {
      log = function() {};
      server.echoback = {
        requestToJSON: requestToJSON,
        requestToHTML: requestToHTML,
        shouldSendJSON: shouldSendJSON,
        handler: handler,
        log: log,
        app: app
      };
    }
    return server;
  };

}).call(this);
