/* globals Twitch */
import getOwner from 'ember-owner/get';
import { moduleFor } from 'ember-qunit';
import MockNotifyService from 'web-client/tests/helpers/mock-notify-service';
import { setupFeatures, teardownFeatures } from './utilities/feature-flagging';
import MockTrackingService from 'web-client/tests/helpers/mock-tracking-service';

import {
  setup as setupMirage, teardown as teardownMirage
} from 'web-client/tests/helpers/setup-mirage-for-integration';
import { setOwnerInjection } from 'web-client/utilities/owner-injection';
import resetStore from 'web-client/tests/helpers/reset-store';
import config from 'web-client/config/environment';

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);
    setOwnerInjection(this.owner.ownerInjection());
    this.owner.register('service:tracking', MockTrackingService);
    this.owner.register('service:notify', MockNotifyService);

    this.owner.lookup('service:intl').setLocale(config.i18n.baseLocale);

    this.featuresSetup = setupFeatures(features);

    // Stub api urls for tests while we run cdn api experiment
    Twitch.api.config.baseUrl = "https://api.twitch.tv";
    Twitch.api.config.baseUrlSecure = "https://api.twitch.tv";
    Twitch.api.config.streamsBaseUrl = "https://api.twitch.tv";
    Twitch.api.config.streamsBaseUrlSecure = "https://api.twitch.tv";
    Twitch.api.config.receiverUrl = "https://api.twitch.tv" + '/crossdomain/receiver.html?v=2';

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

  let afterEach = callbacks.afterEach;
  callbacks.afterEach = function() {
    this.owner.lookup('service:tracking').resetInvocations();
    this.owner.lookup('service:notify').resetInvocations();

    return teardownFeatures(this.featuresSetup)
      .then(() => {
        teardownMirage(this);
        resetStore();

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

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