import Route from 'ember-route';
import injectService from 'ember-service/inject';
import $ from 'jquery';

const EXTENSIONS_DISABLED_ROUTE = 'settings.profile';
const EXTENSION_DISCOVERY_ROUTE = 'settings.extensions.index';
const EXTENSION_CONFIG_ROUTE = 'settings.extensions.configure';

export default Route.extend({
  session: injectService(),
  experiments: injectService(),

  beforeModel(transition) {
    this._super(...arguments);
    if (!this.get('session.isAuthenticated')) {
      transition.abort();
      $.login({ mpSourceAction: 'page-requires-login' });
    }

    let isStaff = this.get('session.userData.is_staff');
    if (!isStaff) {
      this.replaceWith(EXTENSIONS_DISABLED_ROUTE);
      return;
    }

    return this.get('experiments').getExperimentValue('EXTENSIONS').then(value => {
      if (value === 'yes') {
        let settingsController = this.controllerFor('settings');
        settingsController.set('showExtensions', true);
        return;
      }

      this.replaceWith(EXTENSIONS_DISABLED_ROUTE);
    });
  },

  setupController(controller, model) {
    controller.setProperties(model);
  },

  getExtension(id) {
    return this.get('store').findRecord('extension', id, { reload: true });
  },

  returnToExtensionDiscovery() {
    this.transitionTo(EXTENSION_DISCOVERY_ROUTE);
  },

  actions: {
    installExtension(extension) {
      let id = this.get('session.userData.id');
      let installedExtension = this.get('store').createRecord('extension-installation', {
        channelId: id,
        extension
      });

      return installedExtension.save().then(() => {
        if (this.isDestroyed) { return; }
        this.refresh();
      });
    },

    uninstallExtension(extensionInstallation) {
      return extensionInstallation.destroyRecord().then(() => {
        if (this.isDestroyed) { return; }
        this.refresh();
      });
    },

    configureExtension(extension) {
      this.transitionTo(EXTENSION_CONFIG_ROUTE, extension.id);
    },

    returnToExtensionDiscovery() {
      this.returnToExtensionDiscovery();
    }
  }
});
