import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { render, find, findAll, focus, triggerKeyEvent } from '@ember/test-helpers';
import { drag }  from 'ember-sortable/test-support/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 focus meal wrappers', async function(assert) {
    await render(hbs`<MealList />`);

    await focus('[data-sortable-handle]');

    assert.equal(find('[data-sortable-handle]'), document.activeElement);
  });

  test('it can reorder meals via keyboard shortcuts', async function(assert) {
    await render(hbs`<MealList />`);

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

    await focus('[data-sortable-handle]'); // Not technically required, but emulates user interaction
    await triggerKeyEvent('[data-sortable-handle]', 'keydown', 'Enter');
    await triggerKeyEvent('[data-sortable-handle]', 'keydown', 'ArrowDown');
    await triggerKeyEvent('[data-sortable-handle]', 'keydown', 'Enter');

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

  test('it can drag and drop meals', async function(assert) {
    await render(hbs`<MealList />`);

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

    await drag('mouse', '[data-sortable-handle]', () => { return { dy: 100, dx: 0 } });

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

  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);
  }
});
