var log4js = require("log4js");
var logger = log4js.getLogger("default-appender");
var jade = require('jade');
var notFoundPageCacheKey = 'pages.errors.http_not_found';

module.exports = function (shoxler) {
	shoxler.app.get('*', function (req, res) {

		function compileAndCacheContent(caching) {
			try {
				var renderer = jade.compileFile(shoxler.PAGES_ROOT + "error404.jade", shoxler.configs.jade);
				logger.debug("Compiling HTTP 404 template");
				var compiled = renderer({title: "404 :: shoxler"});
				if (caching) {
					shoxler.cache_put(notFoundPageCacheKey, compiled, shoxler.CACHE_MAX_EXPIRE);
					logger.debug('HTTP 404 template compiled and cached');
				}
				res.send(compiled).end();
			} catch (e) {
				logger.error(e.message);
			}
		}

		function handleCachedContent(err, data) {
			if (!err && typeof data != "undefined" && data != null) {
				logger.debug("page served from cache");
				res.set('Content-Type', 'text/html').send(data).end();
			} else {
				logger.info("page is not available in cache");
				compileAndCacheContent(shoxler.configs.server.caching);
			}
		}

		logger.debug("serving page 404");
		res.status(shoxler.HTTP.HTTP_NOT_FOUND);
		if (shoxler.configs.server.caching) {
			shoxler.cache_get(notFoundPageCacheKey, handleCachedContent);
		} else {
			compileAndCacheContent(shoxler.configs.server.caching);
		}
	});
};
