var patchTemplate = ";(" +function() {
    // automatically generated by architect-build
    // bundle all dependencies in the main package
    var Module = require("module");
    var path = require("path");
    var _resolveFilename_orig = Module._resolveFilename
    var root = path.join(__dirname, "{root}");
    Module._resolveFilename = function(id, parent) {
        if (parent && parent.paths && parent.paths[0] && parent.paths[0].indexOf(root) == 0) {
            parent.paths = parent.paths.map(function(p) {
                if (p.indexOf(root) != 0) return
                p = p.slice(root.length);
                return root + p.replace(/([\\\/]|^)node_modules([\\\/]|$)/g, "$1n_m$2");
            }).filter(Boolean);
        }
        return _resolveFilename_orig.call(Module, id, parent);
    };
} + ")();";

//////////////////////////////////////////////////////////////////////////

var fs = require("fs");
var copy = require("architect-build/copy");
var pathLib = require("path");

function freeze(path, mode) {
    path = copy.convertPath(path);
    var pkgs = {};
    function freezePkg(path) {
        if (!pkgs[path]) {
            pkgs[path] = JSON.parse(fs.readFileSync(path + "/package.json"))
            Object.keys(pkgs[path]).forEach(function(k) {
                if (/Dependencies/i.test(k)) delete pkgs[path][k];
            })
        }
        pkgs[path].dependencies = {};
        var deps = fs.existsSync(path + "/node_modules") ? fs.readdirSync(path + "/node_modules") : [];
        deps.forEach(function(n) {
            if (n == ".bin") return;
            var depPath = path +  "/node_modules/" + n;
            freezePkg(depPath);
            pkgs[path].dependencies[n] = pkgs[depPath].version;
        });
        if (mode == "rename") {
            if (deps.length) {
                fs.renameSync(path +  "/node_modules/", path +  "/n_m")
                delete pkgs[path].dependencies
                if (pkgs[path].files)
                    pkgs[path].files.push("n_m")
            }
        } else {
            pkgs[path].bundledDependencies = Object.keys(pkgs[path].dependencies);
        }
        fs.writeFileSync(path + "/package.json", JSON.stringify(pkgs[path], null, "\t"), "utf8");
    }
    freezePkg(path);
    var bin = pkgs[path].bin;
    Object.keys(bin).forEach(function(key) {
        var p = bin[key];
        var root = pathLib.relative(pathLib.dirname(p), "").replace(/[\\]/g, "/");
        var src = fs.readFileSync(path + "/" + p, "utf8");
        src = src.replace(/^(#.*|"use strict";?|\s)*/, function(a) {
            return a.trim() + "\n\n" + patchTemplate.replace(/{root}/g, root) + "\n\n";
        });
        fs.writeFileSync(path + "/" + p, src, "utf8");
    });
}

module.exports = freeze;
