import injectService from 'ember-service/inject';
import UserIdleService from 'ember-user-activity/services/user-idle';
import ContextBoundTasksMixin from 'web-client/mixins/context-bound-tasks';
import RSVP from 'rsvp';

export default UserIdleService.extend(ContextBoundTasksMixin, {
  IDLE_TIMEOUT: 60 * 1000, // once a minute
  MONITOR_TASK_NAME: 'TimeSpent#monitor',
  ENABLED_ROUTES: ['feed', 'directory.following.index', 'dashboards.index', 'index'],
  playerRegistry: injectService(),
  tracking: injectService(),
  routing: injectService('-routing'),

  monitor() {
    this.runTask(() => {
      this.poll();
    }, Math.random() * this.get('IDLE_TIMEOUT')); // this way sub-minute sessions are probabilistically tracked as well
  },

  poll() {
    this.pollTask((next) => {
      this.sendPayload();
      this.runTask(next, this.get('IDLE_TIMEOUT'));
    }, this.get('MONITOR_TASK_NAME'));
  },

  sendPayload() {
    if (!this.ENABLED_ROUTES.includes(this.get('routing.currentRouteName'))) {
      return RSVP.resolve(false);
    }

    this.get('tracking').trackEvent({
      services: ['spade'],
      event: 'time_spent',
      data: {
        is_active: !this.get('isIdle'),
        is_video_playing: this.get('playerRegistry').isAnyPlaying()
      }
    });

    return RSVP.resolve(true);
  }
});
