import ExtensionsBaseRoute from './base';
import RSVP from 'rsvp';
import PanelModel from 'web-client/models/panel';
import injectService from 'ember-service/inject';

export default ExtensionsBaseRoute.extend({
  api: injectService(),

  model() {
    this._super(...arguments);

    let userData = this.get('session.userData');
    let areExtensionsEnabled = this.get('experiments').getExperimentValue('EXTENSIONS').then(value => {
      return value === 'yes' && userData.is_staff;
    });
    let allExtensions = this.get('store').findAll('extension').then(
      extensions => extensions,
      () => []
    );

    let installedExtensions = this.get('store').query('extension-installation', {
      channelId: userData.id
    }).then(
      extensions => extensions,
      () => []
    );

    let panels = PanelModel.find('user', { user: userData.login });
    let extensionPanels = panels.load(true).then(function(data) {
      return data.content.filter(panel => panel.kind && panel.kind.startsWith('ext-'));
    });

    return RSVP.hash({
      areExtensionsEnabled,
      allExtensions,
      installedExtensions,
      extensionPanels
    });
  },

  actions: {
    activateExtension(extensionInstallation, config) {
      let model = this.modelFor(this.routeName);
      let slotPromise;
      if (config.slot) {
        slotPromise = RSVP.resolve(config.slot);
      } else {
        // TODO(rudderm): Panel's `data` field appears to work with any set of fields,
        // so we should migrate to use a static `extension` kind and use only the
        // `slot` field for matching extensions with their slot. Will tackle this separately
        // when adding activation support to panels UI.
        let extensionId = extensionInstallation.get('extension.id');
        let kind = `ext-${extensionId}`;
        let panels = model.extensionPanels || [];
        let panel = panels.find(extPanel => extPanel.kind === kind);
        if (panel) {
          slotPromise = RSVP.resolve(kind);
        } else {
          let api = this.get('api');
          let login = this.get('session.userData.login');
          slotPromise = api.request('post', `/api/channels/${login}/panels`, {
            kind,
            data: { slot: kind }
          }).then(() => {
            return kind;
          });
        }
      }

      return slotPromise.then(slot => {
        extensionInstallation.set('active', true);
        extensionInstallation.set('config', { slot });
        extensionInstallation.save().then(() => {
          if (this.isDestroyed) { return; }
          this.refresh();
        });
      });
    },

    deactivateExtension(extensionInstallation) {
      extensionInstallation.set('active', false);
      extensionInstallation.save().then(() => {
        if (this.isDestroyed) { return; }
        this.refresh();
      });
    }
  }
});
