(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(consumer) {
      var consumerDisposable, value, version, _i, _len, _ref1;
      _ref1 = Object.keys(this.servicesByVersion).sort(semver.rcompare);
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        version = _ref1[_i];
        if (semver.satisfies(version, consumer.versionRange)) {
          if (value = getValueAtKeyPath(this.servicesByVersion[version], consumer.keyPath)) {
            consumerDisposable = consumer.callback.call(null, 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);
