import Service from 'ember-service';
import Ember from 'ember';

const { Evented, assert, run } = Ember;

export let timerDuration = 1000 * 60 * 5;

export function changeTimerDuration(millis) {
  timerDuration = millis;
}

// this is consumed by the route mixin: watched-channels
export default Service.extend(Evented, {
  _timeout: null,

  start() {
    assert('Cannot start service:timer if it is already running', !this._timeout);

    // Using Ember.run will prevent acceptance tests from
    // finishing because they wait for any scheduled timers in
    // the runloop.
    this._timeout = setTimeout(() => {
      run(this, 'trigger', 'timesUp');
    }, timerDuration);
  },

  stop() {
    clearTimeout(this._timeout);
    this._timeout = null;
  },

  willDestroy() {
    this._super(...arguments);
    this.stop();
  }
});
