import getOwner from 'ember-owner/get';
import { moduleForModel } from 'ember-qunit';
import { setupFeatures, teardownFeatures } from './utilities/feature-flagging';

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

  callbacks = callbacks || {};

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

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

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

  let afterEach = callbacks.afterEach;
  callbacks.afterEach = function() {
    return teardownFeatures(featuresSetup)
      .then(() => {
        if (afterEach) {
          return afterEach.apply(this, arguments);
        }
      });
  };

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