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

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

  SemVer = require('semver').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 = {};
      this.versions = [];
      for (version in servicesByVersion) {
        service = servicesByVersion[version];
        this.servicesByVersion[version] = {};
        this.versions.push(new SemVer(version));
        setValueAtKeyPath(this.servicesByVersion[version], keyPath, service);
      }
      this.versions.sort(function(a, b) {
        return b.compare(a);
      });
    }

    Provider.prototype.provide = function(consumer) {
      var consumerDisposable, value, version, _i, _len, _ref1;
      _ref1 = this.versions;
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        version = _ref1[_i];
        if (consumer.versionRange.test(version)) {
          if (value = getValueAtKeyPath(this.servicesByVersion[version.toString()], 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);
