import { moduleForComponent, test } from 'ember-qunit';
import Service from 'ember-service';
import hbs from 'htmlbars-inline-precompile';
import sinon from 'sinon';
import PhoenixLib from 'npm:twitch-phoenix';

const Phoenix = PhoenixLib.Phoenix;
const USER_ID = '1';

const phoenixServiceStub = Service.extend({
  _store: {}
});

moduleForComponent('react-component', 'Integration | Component | react-component', {
  integration: true,

  beforeEach() {
    this.register('service:phoenix', phoenixServiceStub);
    this.inject.service('phoenix');

    Phoenix.FooComponent = () => {};

    this.fakeStore = {};
    this.get('phoenix').set('_store', this.fakeStore);

    this.reactProviderSpy = sinon.stub(Phoenix, 'reactProvider');
    this.fooComponentSpy = sinon.stub(Phoenix, 'FooComponent');
    this.unmountComponentSpy = sinon.stub(Phoenix, 'unmountComponent');

    this.set('userId', USER_ID);
    this.render(hbs`
      {{react-component component='FooComponent' userId=userId}}
    `);
  },

  afterEach() {
    this.reactProviderSpy.restore();
    this.fooComponentSpy.restore();
    this.unmountComponentSpy.restore();

    delete Phoenix.FooComponent;
    Phoenix.store = this.actualStore;
  }
});

test('it renders a react component', function (assert) {
  let expectedProps = {
    userId: USER_ID
  };

  assert.ok(this.reactProviderSpy.calledWith(
    this.$('.react')[0],
    this.fakeStore,
    this.fooComponentSpy,
    expectedProps
  ));
});

test('it un-mounts the react component when the component is destroyed', function (assert) {
  let expectedRootElement = this.$('.react')[0];
  this.clearRender();

  assert.ok(this.unmountComponentSpy.calledWith(expectedRootElement));
});
