// Generated by CoffeeScript 1.10.0
(function() {
  var getReplacement, path, transformTools;

  path = require('path');

  transformTools = require('browserify-transform-tools');

  getReplacement = function(file, aliases, regexps) {
    var fileParts, key, pkg, re;
    if (regexps != null) {
      for (key in regexps) {
        re = new RegExp(key);
        if (re.test(file)) {
          if (regexps[key] === false) {
            return false;
          } else if (typeof regexps[key] === "function") {
            return regexps[key](file, key, re);
          } else {
            return file.replace(re, regexps[key]);
          }
        }
      }
    }
    if (aliases != null) {
      if (file in aliases) {
        return aliases[file];
      } else {
        fileParts = /^([^\/]*)(\/.*)$/.exec(file);
        if ((fileParts != null ? fileParts[1] : void 0) in aliases) {
          pkg = aliases[fileParts != null ? fileParts[1] : void 0];
          if (pkg === false) {
            return false;
          } else if (pkg != null) {
            return pkg + fileParts[2];
          }
        }
      }
    }
    return null;
  };

  module.exports = transformTools.makeRequireTransform("aliasify", {
    jsFilesOnly: true,
    fromSourceFileDir: true
  }, function(args, opts, done) {
    var aliases, configDir, file, fileDir, ref, regexps, replacement, result, verbose;
    if (!opts.config) {
      return done(new Error("Could not find configuration for aliasify"));
    }
    aliases = opts.config.aliases;
    regexps = opts.config.replacements;
    verbose = opts.config.verbose;
    configDir = ((ref = opts.configData) != null ? ref.configDir : void 0) || opts.config.configDir || process.cwd();
    result = null;
    file = args[0];
    if ((file != null) && ((aliases != null) || (regexps != null))) {
      replacement = getReplacement(file, aliases, regexps);
      if (replacement === false) {
        result = "{}";
      } else if (replacement != null) {
        if (replacement.relative != null) {
          replacement = replacement.relative;
        } else if (/^\./.test(replacement)) {
          replacement = path.resolve(configDir, replacement);
          fileDir = path.dirname(opts.file);
          replacement = "./" + (path.relative(fileDir, replacement));
        }
        if (verbose) {
          console.error("aliasify - " + opts.file + ": replacing " + args[0] + " with " + replacement);
        }
        if (/^[a-zA-Z]:\\/.test(replacement)) {
          replacement = replacement.replace(/\\/gi, "\\\\");
        } else {
          replacement = replacement.replace(/\\/gi, "/");
        }
        result = "require('" + replacement + "')";
      }
    }
    return done(null, result);
  });

}).call(this);
