import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { render, find, findAll, click, triggerEvent } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';

module('Integration | Component | meal-list', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(initMeals);

  test('it renders existing meals into a list', async function(assert) {
    await render(hbs`<MealList />`);

    assert.dom('[data-test-id=meal-item]').exists({ count: 2 });
  });

  test('it can reorder items via sort up/down links', async function(assert) {
    await render(hbs`<MealList />`);
    let element = find('[data-test-id=meal-list-wrapper]');
    await triggerEvent(element, 'focus');
    await click('[data-test-id=sort-down]');

    assert.dom(findAll('[data-test-id=meal-name]')[0]).includesText('Meal 2');
    assert.dom(findAll('[data-test-id=meal-name]')[1]).includesText('Meal 1');

    await click('[data-test-id=sort-up]');
    assert.dom(findAll('[data-test-id=meal-name]')[0]).includesText('Meal 1');
    assert.dom(findAll('[data-test-id=meal-name]')[1]).includesText('Meal 2');
  });

  async function initMeals() {
    let store = this.owner.lookup('service:store');
    let meal = {
      area: 'area',
      category: 'category',
      ingredients: [
        { name: 'Love', measure: 'Infinity' },
        { name: 'Chocolate', measure: 'As much as you like!' },
      ],
    };
    this.server.create('meal', Object.assign({}, meal, { name: 'Meal 1', id: 1 }));
    this.server.create('meal', Object.assign({}, meal, { name: 'Meal 2', id: 2 }));
    await store.findRecord('meal', 1);
    await store.findRecord('meal', 2);
  }
});
