import getOwner from 'ember-owner/get';
import { moduleFor } from 'ember-qunit';
import { setupFeatures, teardownFeatures } from './utilities/feature-flagging';
import {
  setup as setupMirage, teardown as teardownMirage
} from 'web-client/tests/helpers/setup-mirage-for-integration';

export default function(name, description, callbacks) {
  if (typeof description === 'object') {
    callbacks = description;
    description = undefined;
  }

  callbacks = callbacks || {};

  if (!callbacks.hasOwnProperty('integration')) {
    callbacks.integration = true;
  }

  let features = callbacks.features || [];
  let beforeEach = callbacks.beforeEach;
  callbacks.beforeEach = function() {
    setupMirage(this);
    this.owner = getOwner(this);
    this.featuresSetup = setupFeatures(features);

    return this.featuresSetup.featureInjector
      .then(() => {
        if (beforeEach) {
          return beforeEach.apply(this, arguments);
        }
      });
  };

  let afterEach = callbacks.afterEach;
  callbacks.afterEach = function() {
    return teardownFeatures(this.featuresSetup)
      .then(() => {
        teardownMirage(this);

        if (afterEach) {
          return afterEach.apply(this, arguments);
        }
      });
  };

  if (description) {
    moduleFor(name, description, callbacks);
  } else {
    moduleFor(name, callbacks);
  }
}
