"use strict";

var browserify = require("browserify"),
    b = browserify(),
    bundles = [];

module.exports = {
    browserify: function(app) {
        return function(req, res, next) {
            // whitelist what we bundle.
            var body, fileName,
                isWhitelisted = false,
                whitelist = ["customer.js"];

            // make sure that it's a validator url, and that we
            // the requested path is whitelisted.  this is just
            // a simple means of protecting against directory
            // traversal attacks and exposing application logic.
            if (req.url.indexOf("/validators/") === 0) {
                var counter = 0;
                fileName = req.url.substring("12");
                for (counter = 0; counter < whitelist.length; counter += 1) {
                    if (fileName === whitelist[counter]) {
                        isWhitelisted = true;
                        break;
                    }
                }

                if (isWhitelisted === true) {
                    // check our cache first
                    if (app.enabled("browserifyCaching") && bundles[fileName]) {
                        body = bundles[fileName];
                    } else {
                        // no cache entry, so bundle this and create one.
                        body = bundles[fileName] = b.require("./validators/" + fileName).bundle();
                    }

                    res.setHeader("Content-Type", "application/javascript");
                    res.setHeader("Content-Length", body.length);
                    res.end(body);
                } else {
                    next();
                }
            } else {
                next();
            }
        };
    }
};