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

var extend = require("extend");

function addRoute(router, config) {
	var base = config.base;

	var view = config.view;
	var versionContents = config.versionContents; //the reference version is included as well

	var actualVersions = config.actualVersions;
	var historicalVerions = config.historicalVerions;

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

	var experimentPage = config.experimentPage;
	var experimentKey = config.experimentKey;

	var route = "/";

	if (base !== "webpage") {
		route += base + "/";
	}

	if (view !== "index") {
		route += view;
	}


	router.get(route, function(req, res) {
		var version = req.query.v || "reference";
		var fullUrl = req.protocol + "://" + req.get("host") + route;

		if (historicalVerions.indexOf(version) > -1) {
			return res.redirect(301, route);
		}

		if (actualVersions.indexOf(version) > -1  && versionContents[version]) {
			res.locals.url = fullUrl;

			res.locals.view = view;
			res.locals.version = version;
			res.locals.base = base;

			res.locals.experimentPage = experimentPage;
			res.locals.experimentKey = experimentKey;

			var actContent = extend(true, {}, versionContents[version][view]);

			actContent.meta = extend(true, {}, meta, actContent.meta);
			actContent.tracking = extend(true, {}, tracking, actContent.tracking);

			return res.render(view, actContent);
		}

		res.status(404).sendFile(path.join(__dirname, "../public/404.html"));
	});
}


module.exports = function (config) {
	var router = express.Router();

	var templateContents = config.templateContents;
	var experiments = config.experiments;

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

	for (var base in templateContents) {
		var actTemplateContents = templateContents[base];
		var actConfig = experiments[base];

		var actualVersions = actConfig.actualExperiment.versions;
		var actualExperimentKey = actConfig.actualExperiment.experimentKey;
		var actualExperimentPage = actConfig.actualExperiment.page;
		var historicalVerions = [];

		actConfig.history.forEach(function(item) {
			item.versions.forEach(function(item) {
				historicalVerions.push(item);
			});
		});

		// call addRoute() for every config file with a routeConfig
		for(var key in actTemplateContents.reference) {
			// prepare route configs
			addRoute(router, {
				base: base,
				view: key,
				versionContents: actTemplateContents,
				actualVersions: actualVersions,
				historicalVerions: historicalVerions,

				meta: meta,
				tracking: tracking,

				experimentPage: actualExperimentPage,
				experimentKey: actualExperimentKey
			});
		}
	}

	return router;
};
