(function() {
  var CompositeDisposable, Disposable, _ref;

  _ref = require('atom'), CompositeDisposable = _ref.CompositeDisposable, Disposable = _ref.Disposable;

  module.exports = {
    config: {
      enabled: {
        type: 'boolean',
        "default": false
      }
    },
    subscriptions: null,
    activate: function() {
      var handleBeforeUnload, handleBlur;
      this.subscriptions = new CompositeDisposable;
      handleBeforeUnload = this.autosaveAllPaneItems.bind(this);
      window.addEventListener('beforeunload', handleBeforeUnload, true);
      this.subscriptions.add(new Disposable(function() {
        return window.removeEventListener('beforeunload', handleBeforeUnload, true);
      }));
      handleBlur = (function(_this) {
        return function(event) {
          if (event.target === window) {
            return _this.autosaveAllPaneItems();
          } else if (event.target.matches('atom-text-editor:not([mini])') && !event.target.contains(event.relatedTarget)) {
            return _this.autosavePaneItem(event.target.getModel());
          }
        };
      })(this);
      window.addEventListener('blur', handleBlur, true);
      this.subscriptions.add(new Disposable(function() {
        return window.removeEventListener('blur', handleBlur, true);
      }));
      return this.subscriptions.add(atom.workspace.onWillDestroyPaneItem((function(_this) {
        return function(_arg) {
          var item;
          item = _arg.item;
          return _this.autosavePaneItem(item);
        };
      })(this)));
    },
    deactivate: function() {
      return this.subscriptions.dispose();
    },
    autosavePaneItem: function(paneItem) {
      if (!atom.config.get('autosave.enabled')) {
        return;
      }
      if ((paneItem != null ? typeof paneItem.getURI === "function" ? paneItem.getURI() : void 0 : void 0) == null) {
        return;
      }
      if (!(paneItem != null ? typeof paneItem.isModified === "function" ? paneItem.isModified() : void 0 : void 0)) {
        return;
      }
      return paneItem != null ? typeof paneItem.save === "function" ? paneItem.save() : void 0 : void 0;
    },
    autosaveAllPaneItems: function() {
      var paneItem, _i, _len, _ref1, _results;
      _ref1 = atom.workspace.getPaneItems();
      _results = [];
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        paneItem = _ref1[_i];
        _results.push(this.autosavePaneItem(paneItem));
      }
      return _results;
    }
  };

}).call(this);
