// Generated by CoffeeScript 1.12.7
(function() {
  var Exclusions, RegexpCache, root;

  RegexpCache = {
    cache: {},
    clear: function(cache) {
      this.cache = cache != null ? cache : {};
    },
    get: function(pattern) {
      if (pattern in this.cache) {
        return this.cache[pattern];
      } else {
        return this.cache[pattern] = (function() {
          try {
            return new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
          } catch (error) {
            BgUtils.log("bad regexp in exclusion rule: " + pattern);
            return /^$/;
          }
        })();
      }
    }
  };

  Exclusions = {
    RegexpCache: RegexpCache,
    rules: Settings.get("exclusionRules"),
    getRule: function(url, rules) {
      var i, len, matchingRules, passKeys, rule;
      if (rules == null) {
        rules = this.rules;
      }
      matchingRules = (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = rules.length; i < len; i++) {
          rule = rules[i];
          if (rule.pattern && 0 <= url.search(RegexpCache.get(rule.pattern))) {
            results.push(rule);
          }
        }
        return results;
      })();
      for (i = 0, len = matchingRules.length; i < len; i++) {
        rule = matchingRules[i];
        if (!rule.passKeys) {
          return rule;
        }
      }
      passKeys = ((function() {
        var j, len1, results;
        results = [];
        for (j = 0, len1 = matchingRules.length; j < len1; j++) {
          rule = matchingRules[j];
          results.push(rule.passKeys.split(/\s+/).join(""));
        }
        return results;
      })()).join("");
      if (0 < matchingRules.length) {
        return {
          passKeys: Utils.distinctCharacters(passKeys)
        };
      } else {
        return null;
      }
    },
    isEnabledForUrl: function(url) {
      var ref, rule;
      rule = Exclusions.getRule(url);
      return {
        isEnabledForUrl: !rule || 0 < rule.passKeys.length,
        passKeys: (ref = rule != null ? rule.passKeys : void 0) != null ? ref : ""
      };
    },
    setRules: function(rules) {
      this.rules = rules.filter(function(rule) {
        return rule && rule.pattern;
      });
      return Settings.set("exclusionRules", this.rules);
    },
    postUpdateHook: function(rules) {
      this.rules = Settings.get("exclusionRules");
      return RegexpCache.clear();
    }
  };

  Settings.postUpdateHooks["exclusionRules"] = Exclusions.postUpdateHook.bind(Exclusions);

  root = typeof exports !== "undefined" && exports !== null ? exports : window;

  extend(root, {
    Exclusions: Exclusions
  });

}).call(this);
