import Component from 'ember-component';
import hbs from 'htmlbars-inline-precompile';
import $ from 'jquery';

/**
 * This is a little weird.
 *
 * Sometimes it's necessary to pass an element from a parent component into
 * a child component. In my case, ember-pikaday can render its calendar UI
 * inside of a provided container element.
 *
 * This component generates an element to be passed into another component
 * during initalization. When didInsertElement hooks fire, this element will
 * be appended to the DOM.
 *
 * An alternative would be to guard rendering the child component with
 * an {{if}}, wait for didInsertElement to fire on the parent, and then
 * render the child, passing in the target element. This would work
 * and provide the same API but would cause 2 renders.
 *
 * Example usage:
 *
 *    {{#yield-element as |element id|}}
 *      {{early-element-user injectedElement=element}}
 *      <div id={{id}}></div>
 *    {{/yield-element}}
 */

// A monotonically increasing ID
let id = 1;

export default Component.extend({
  tagName: '',

  init() {
    this._super(...arguments);
    this.elementToYield = document.createElement('DIV');
    this.placeholderId = `yield-element-placeholder-${id++}`;
  },

  layout: hbs`
    {{yield elementToYield placeholderId}}
  `,

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

    $(`#${this.placeholderId}`).append(this.elementToYield);
  }
});
