import Component from 'ember-component';
import injectService from 'ember-service/inject';
import { assert } from 'ember-metal/utils';

import PhoenixLib from 'npm:twitch-phoenix';

// The way in which we build our PhoenixLib doesn't seem to play nicely with
// Ember's import system. Revisit trying to get named exports working with
// standard ES6 destructuring syntax.
const Phoenix = PhoenixLib.Phoenix;
const COMPONENT_SPECIFIER = 'component';

export default Component.extend({
  phoenix: injectService(),

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

    let rootEl = this.get('element');
    this.set('reactRootEl', rootEl.querySelector('.react'));

    let attrs = this.get('attrs');
    let specifiedProperties = Object.keys(this.get('attrs')).reduce((propSet, attributeKey) => {
      if (attributeKey !== COMPONENT_SPECIFIER) {
        propSet[attributeKey] = attrs[attributeKey].value;
      }
      return propSet;
    }, {});

    this._mountComponent(
      this.get('reactRootEl'),
      this.get(COMPONENT_SPECIFIER),
      specifiedProperties
    );
  },

  willDestroyElement() {
    this._unmountComponent(this.get('reactRootEl'));
    this._super(...arguments);
  },

  _mountComponent(element, reactComponentName, props) {
    let component = Phoenix[reactComponentName];

    if (!component || (typeof component !== 'function')) {
      assert(`${this}: requires reactComponentName to map to an exported Phoenix Component `, reactComponentName);
      return;
    }

    Phoenix.reactProvider(element, this.get('phoenix').get('_store'), component, props);
  },

  _unmountComponent(element) {
    Phoenix.unmountComponent(element);
  }
});
