{"size": 1610, "ext": "js", "max_stars_repo_path": "addon/core/connection_monitor.js", "max_stars_repo_name": "ScaleFactor/ember-cable", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "addon/core/connection_monitor.js", "max_issues_repo_name": "ScaleFactor/ember-cable", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "addon/core/connection_monitor.js", "max_forks_repo_name": "ScaleFactor/ember-cable", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 20.641025641, "max_line_length": 117, "alphanum_fraction": 0.6105590062}
import Ember from 'ember';

var ConnectionMonitor = Ember.Object.extend({
  connection: null,
  stoppedAt: null,
  startedAt: null,
  pingedAt: null,
  disconnectedAt: null,
  staleThreshold: 6,
  reconnectAttempts: 0,

  init() {
    this._super(...arguments);
    this.start();
  },

  start() {
    this.reset();
    this.set('stoppedAt', null);
    this.set('startedAt', Date.now());
    this.poll();
  },

  connected() {
    this.reset();
    this.set('pingedAt', Date.now());
    this.set('disconnectedAt', null);
  },

  disconnected() {
    this.set('disconnectedAt', Date.now());
  },

  ping() {
    this.set('pingedAt', Date.now());
  },

  reset() {
    this.set('reconnectAttempts', 0);
  },

  poll() {
    Ember.run.later(this, () => {
      this.reconnectIfStale();
      this.poll();
    }, this.interval());
  },

  interval() {
    return Math.max(3, Math.min(30, 5 * Math.log(this.get('reconnectAttempts') + 1) )) * 1000;
  },

  reconnectIfStale() {
    if(this.connectionIsStale()) {
      this.incrementProperty('reconnectAttempts');
      if(!this.disconnectedRecently()) {
        this.get('connection').reopen();
      }
    }
  },

  connectionIsStale() {
    return this.secondsSince(this.get('pingedAt') || this.get('startedAt')) > this.get('staleThreshold');
  },

  disconnectedRecently() {
    return this.get('disconnectedAt') && this.secondsSince(this.get('disconnectedAt') ) < this.get('staleThreshold');
  },

  secondsSince(time) {
    return (Date.now() - time) / 1000;
  }
});

ConnectionMonitor[Ember.NAME_KEY] = 'ConnectionMonitor';

export default ConnectionMonitor;
