(function() {
  var CompositeDisposable, Provider, getValueAtKeyPath, semver, setValueAtKeyPath, _ref;

  CompositeDisposable = require('event-kit').CompositeDisposable;

  semver = require('semver');

  _ref = require('./helpers'), getValueAtKeyPath = _ref.getValueAtKeyPath, setValueAtKeyPath = _ref.setValueAtKeyPath;

  module.exports = Provider = (function() {
    function Provider(keyPath, servicesByVersion) {
      var service, version;
      this.consumersDisposable = new CompositeDisposable;
      this.servicesByVersion = {};
      for (version in servicesByVersion) {
        service = servicesByVersion[version];
        this.servicesByVersion[version] = {};
        setValueAtKeyPath(this.servicesByVersion[version], keyPath, service);
      }
    }

    Provider.prototype.provide = function(_arg) {
      var callback, consumerDisposable, keyPath, value, version, versionRange, _i, _len, _ref1;
      keyPath = _arg.keyPath, versionRange = _arg.versionRange, callback = _arg.callback;
      _ref1 = Object.keys(this.servicesByVersion).sort(semver.rcompare);
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        version = _ref1[_i];
        if (semver.satisfies(version, versionRange)) {
          if (value = getValueAtKeyPath(this.servicesByVersion[version], keyPath)) {
            consumerDisposable = callback(value);
            if (typeof (consumerDisposable != null ? consumerDisposable.dispose : void 0) === 'function') {
              this.consumersDisposable.add(consumerDisposable);
            }
            return;
          }
        }
      }
    };

    Provider.prototype.destroy = function() {
      return this.consumersDisposable.dispose();
    };

    return Provider;

  })();

}).call(this);
