import moduleForComponent from 'web-client/tests/helpers/module-for-component';
import { test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import Component from 'ember-component';
import ClickOutsideMixin from 'web-client/mixins/click-outside';

const ClickOutsideTestComponent = Component.extend(ClickOutsideMixin, {
  isMenuOpen: false,
  clickedOutside() {
    if (this.get('isMenuOpen')) {
      this._toggleMenu();
    }
  },

  _toggleMenu() {
    this.toggleProperty('isMenuOpen');
  }
});

const ClickOutsideTestComponentWithoutMethod = Component.extend(ClickOutsideMixin, {
  isMenuOpen: false,

  _toggleMenu() {
    this.toggleProperty('isMenuOpen');
  }
});

moduleForComponent('click-outside', {
  integration: true,

  beforeEach() {
    this.owner.register('component:click-outside-test', ClickOutsideTestComponent);
    this.owner.register('template:components/click-outside-test', hbs`
      {{#if isMenuOpen}}
        <div class="is-menu-open"></div>
      {{else}}
        <button class="show-menu"></button>
      {{/if}}
      <button class="inside-test">Click Me</button>
    `);

    this.isShowingMenu = () => {
      return this.$('.is-menu-open').length === 1;
    };
  }
});

test('clicking inside does not toggle', function(assert) {
  // Template block usage:
  this.render(hbs`
    <button class="outside-test">Click Me</button>

    {{click-outside-test isMenuOpen=true}}
  `);

  this.$('.inside-test').click();

  assert.ok(this.isShowingMenu(), 'shows menu after clicking');
});

test('clicking outside does toggle', function(assert) {
  // Template block usage:
  this.render(hbs`
    <button class="outside-test">Click Me</button>

    {{click-outside-test isMenuOpen=true}}
  `);

  this.$('.outside-test').click();

  assert.notOk(this.isShowingMenu(), 'does not show menu after clicking outside');
});

test('component with mixin must implement "clickedOutside"', function(assert) {
  assert.throws(() => {
    this.owner.register('component:click-outside-test', ClickOutsideTestComponentWithoutMethod);

    this.render(hbs`{{click-outside-test isMenuOpen=true}}`);
  }, /Component .* must implement "clickedOutside"./);
});
