var path = require("path");

var cookieParser = require("cookie-parser"),
    errorhandler = require("errorhandler"),
    morgan = require("morgan"),
    serveStatic = require("serve-static"),
    session = require("express-session"),
    webpack = require("webpack"),
    webpackMiddleware = require("webpack-dev-middleware");

module.exports = function(app) {
  var webpackCompiler = webpack({
    cache: true,
    entry: path.join(app.get("root"), "client", "app.jsx"),
    devtool: "inline-source-map",
    output: {
      path: path.join(app.get("root"), "public"),
      filename: "bundle.js"
    },
    module: {
      loaders: [
        { test: /\.jsx$/, loader: "jsx", include: path.join(app.get("root"), "client") },
        { test: /\.less$/, loader: "style!css!less" }
      ]
    }
  });

  if (process.env.NODE_ENV === "production") {
    app.use(morgan());
  } else {
    app.use(morgan({ format: 'dev', immediate: true }));
    app.use(webpackMiddleware(webpackCompiler, {
      noInfo: true,
      quiet: false,
      lazy: false,
      filename: "bundle.js",
      watchDelay: 150
    }));
  }

  app.use(serveStatic("public", {index: ["index.html"]}))
  app.use(cookieParser());
  app.use(session({
    secret: "6EUh1JPkbM51Uv2KMbIReexxK827Q06G",
    name: "fluxxor-chat-demo-sid",
    saveUninitialized: true,
    resave: true
  }));
};
