var fs = require("fs");
var ejs = require("ejs");
var path = require("path");
var express = require("express");

var readTemplateContents = require("./routes/prepareTemplateContents");
var createRouter = require("./routes/routes");
var createSubscribeRouter = require("./routes/subscribeRoutes");

module.exports = function(config) {
	// PREPARE TEMPLATE CONTENTS
	var experiments = config.experiments;
	var templateContents = readTemplateContents(config);

	var meta = config.meta;
	var tracking = config.tracking;

	var viewsPath = config.viewsPath;
	var defaultPath = "./defaultViews";

	var app = config.app;
	app.set("views", [viewsPath, path.join(__dirname, "./defaultViews")]);
	app.use(express.static(path.join(__dirname, "./public")));

	ejs.resolveInclude = function(name, filename, isDir) {
		var dirname = path.dirname;
		var extname = path.extname;
		var resolve = path.resolve;
		var includePath = resolve(isDir ? filename : dirname(filename), name);
		var ext = extname(name);

		var path1 = path.join(viewsPath, name);
		var path2 = path.join(__dirname, defaultPath, name);

		if (!ext) {
			includePath += ".ejs";
			
			path1 += ".ejs";
			path2 += ".ejs";
		}

		if (fs.existsSync(includePath)) {
			return includePath;
		}

		if (fs.existsSync(path1)) {
			return path1;
		}

		return path2;
	};

	// ROUTES
	var router = createRouter({
		experiments: experiments,
		templateContents: templateContents,

		meta: meta,
		tracking: tracking
	});

	var subscribeRouter = createSubscribeRouter(config.subscribeRoutes);

	router.use("/", subscribeRouter);

	return router;
};
