import "isomorphic-fetch";

const express = require("express");
const path = require("path");
const Chalk = require("chalk");
const favicon = require("serve-favicon");

const appConfig = require("../config/main");
const app = express();

if (process.env.NODE_ENV !== "production") {
  const webpack = require("webpack");
  const webpackConfig = require("../config/webpack/dev");
  const webpackCompiler = webpack(webpackConfig);

  app.use(require("webpack-dev-middleware")(webpackCompiler, {
    lazy: false,
    logLevel: "info",
    publicPath: webpackConfig.output.publicPath,
    stats: {colors: true}
  }));

  app.use(require("webpack-hot-middleware")(webpackCompiler));
}

app.use(favicon(path.join(__dirname, "public/favicon.ico")));

app.use("/public", express.static(path.join(__dirname, "public")));

app.get("*", (_, res) => {
  res.sendFile(path.resolve("./build/index.html"), {}, (error) => {
    if (error) {
      console.error(error.message);
    }
  });
});

app.listen(appConfig.port, appConfig.host, (err) => {
  if (err) {
    console.error(Chalk.bgRed(err));
  } else {
    console.info(Chalk.black.bgGreen(
      `\n\n💂  Listening at http://${appConfig.host}:${appConfig.port}\n`
    ));
  }
});
