import QUnit from 'qunit';
import Ember from 'ember';

const { getOwner } = Ember;

function _getOwner() {
  let context = QUnit.config.current.testEnvironment;

  // getOwner(context) is set by ember-qunit for integration and unit tests
  // context.owner is set by our tests/helpers/module-for-acceptance.js for acceptance tests
  return getOwner(context) || context.owner;
}

QUnit.assert.trackInteractivity = function (routeName) {
  let service = _getOwner().lookup('service:interactivity');
  let monitorInvocations = service._monitorInvocations;
  let isInteractive;
  let message = `The ${routeName} route successfully monitored interactivity`;

  let subscribed = monitorInvocations.some((invocation) => {
    if (invocation.name === routeName) {
      isInteractive = invocation.isInteractive;
      return true;
    }
    message = `The ${routeName} route did not initiate monitoring in the interactivity service`;
    return false;
  });

  let interactive = false;
  if (subscribed) {
    interactive = isInteractive(service._interactiveComponents);
    if (!interactive) {
      message = `The interactivity conditions were not satisfied for the ${routeName} route`;
    }
  }

  let result = subscribed && interactive;

  this.pushResult({
    result,
    actual: result,
    expected: true,
    message
  });
};
