import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click, settled, typeIn } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';

module('Integration | Helper | debounce', function(hooks) {
	setupRenderingTest(hooks);

	test('Debounces the action calls', async function(assert) {
		this.set('actionToCall', function() {
			assert.step('clicked');
		});

		await render(hbs`
      {{!-- template-lint-disable data-qid-interactive --}}
      <button type="button"
				{{on 'click' (debounce this this.actionToCall timeout=100)}}
			>Click Me</button>
		`);

		// Don't wait here, we want to click a bunch and wait for settled later
		click('button');
		click('button');
		click('button');
		click('button');
		await settled();
		assert.verifySteps(['clicked']);
	});

	test('Doesnt error when the context is gone', async function(assert) {
		this.set('actionToCall', function() {
			assert.step('clicked');
		});

		await render(hbs`
			{{!-- template-lint-disable data-qid-interactive --}}
      <button type="button"
				{{on 'click' (debounce this this.actionToCall timeout=100)}}
			>Click Me</button>
		`);

		click('button'); // Don't wait because we want the test to finish
		assert.verifySteps([]);
	});

	test('Works on an input as well', async function(assert) {
		this.set('value', null);
		this.set('setValue', function(value) {
			assert.step(value);
			this.set('value', value);
		});

		await render(hbs`
      {{!-- template-lint-disable require-input-label --}}
      <input
				data-qid-input
				value={{this.value}}
				{{on 'keyup' (pick 'target.value' (debounce this this.setValue timeout=100))}}
			/>
		`);

		await typeIn('[data-qid-input]', 'farm');
		assert.verifySteps(['farm']);
		assert.equal(this.value, 'farm');
	});
});