import moduleForComponent from 'web-client/tests/helpers/module-for-component';
import { test } from 'ember-qunit';
import Model from 'ember-data/model';
import Adapter from 'ember-data/adapter';
import attr from 'ember-data/attr';
import run from 'ember-runloop';
import hbs from 'htmlbars-inline-precompile';
import RSVP from 'rsvp';

moduleForComponent('committed-attr', {
  beforeEach() {
    this.owner.register('model:dummy', Model.extend({
      name: attr()
    }));

    this.owner.register('adapter:dummy', Adapter.extend({
      findRecord() {
        return RSVP.resolve({
          data: {
            type: 'dummy',
            id: 1,
            attributes: {
              name: "Server Name"
            }
          }
        });
      },

      updateRecord() {
        return RSVP.resolve();
      }
    }));
  }
});

test("renders a model's committed attribute", function(assert) {
  assert.expect(3);

  this.store = this.owner.lookup('service:store');

  return run(() => this.store.findRecord('dummy', 1)).then((model) => {
    this.set('model', model);
    this.render(hbs`{{committed-attr model 'name'}}`);

    assert.equal(this.$().text(), 'Server Name', 'Renders the name from the server');
    this.set('model.name', 'New Name');

    assert.equal(this.$().text(), 'Server Name', 'Still renders the committed attribute');

    return run(() => this.model.save());
  }).then(() => {
    assert.equal(this.$().text(), 'New Name', 'Renders a new name after the server has aknowledged');
  });
});

test("works with multiple helpers listening", function(assert) {
  assert.expect(2);

  this.store = this.owner.lookup('service:store');

  return run(() => this.store.findRecord('dummy', 1)).then((model) => {
    this.set('model', model);
    this.render(hbs`
      <p>{{committed-attr model 'name'}}</p>
      <p>{{committed-attr model 'name'}}</p>
    `);
    this.set('model.name', 'New Name 1');

    return run(() => this.model.save());
  }).then(() => {
    assert.deepEqual(getText(this.$('p')), ['New Name 1', 'New Name 1'], 'Renders new names after the server has aknowledged');
    this.set('model.name', 'New Name 2');

    return run(() => this.model.save());
  }).then(() => {
    assert.deepEqual(getText(this.$('p')), ['New Name 2', 'New Name 2'], 'Renders new names again after the server has aknowledged');
  });
});

function getText(jqElement) {
  return jqElement.toArray().map(el => el.textContent.trim());
}
