'use strict';

const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const createEventStream = require("./event-stream");

function projectPath(targetPath) {
	return path.resolve(__dirname, "../..", targetPath);
}

module.exports = function () {
	let eventStream = createEventStream();

	let app = express();

	app.set("view engine", "pug");
	app.set("views", projectPath("src/server/views"));

	app.use(express.static(projectPath("public")));

	app.use(bodyParser.urlencoded({
		extended: true
	}));

	app.use("/", require("./routes/index"));

	app.post("/add-source", (req, res) => {
		eventStream.reportNewTask({
			type: "add-source",
			url: req.body.url
		});

		res.json({});
		// res.json({
		// 	source: req.body.url
		// });
	});

	app.use((err, _req, res, _next) => {
		res.render("error", {
			error: err
		});
	});

	return app;
};
