import focus from 'web-client/tests/helpers/focus';

export default class Search {
  constructor(context) {
    this.context = context;
  }

  get panel() {
    return $('#wormhole-overlays .search-panel');
  }

  get hasPanel() {
    return !!this.panel.length;
  }

  get isShowingErrorMessage() {
    return this.panel.find('[data-test-selector=search-error-message]').length === 1;
  }

  get isShowingSpinner() {
    return this.panel.find('.loading-spinner').length === 1;
  }

  get input() {
    return this.context.$('input');
  }

  get gamesHeader() {
    return this.panel.find('[data-test-selector=games-header]');
  }

  get backButton() {
    return this.panel.find('[data-test-selector=panel-remove-current-filter]');
  }

  get filterIcon() {
    return this.context.$('[data-test-selector=filter-icon]');
  }

  get hasFilterIcon() {
    return !!this.filterIcon.length;
  }

  get panelHeader() {
    return this.panel.find('[data-test-selector=panel-header]').text().trim();
  }

  get panelBodyNoResults() {
    return this.panel.find('[data-test-selector=panel-body-no-results]').text().trim();
  }

  get panelResultsVisibility() {
    return this.panel.find('.tse-content').css('visibility');
  }

  get titleSeparators() {
    let separators = this.panel.find('[data-test-selector=title-separator]').toArray();
    return separators.map(s => s.innerHTML.trim());
  }

  get isInputFocused() {
    return document.activeElement === this.input[0];
  }

  blurInput() {
    this.input.blur();
  }

  focusInput() {
    focus(this.input);
  }

  clickGame(title) {
    this.panel.find(`[data-test-selector=games-hits] a:contains(${title})`).click();
  }

  bodyClick() {
    $('body').trigger('click');
  }

  enterTerm(term) {
    this.focusInput();
    this.context.$('input').val(term).trigger('input');
  }

  get searchHits() {
    return {
      games: this.queryContentTitles('[data-test-selector=games-hits] h5'),
      channels: this.queryContentTitles('[data-test-selector=channel-hit-name]'),
      users: this.queryContentTitles('[data-test-selector=users-hits] h5'),
      vods: this.queryContentTitles('[data-test-selector=videos-hits] h5')
    };
  }

  queryContentTitles(selector) {
    return this.panel.find(selector).toArray().map((el) => {
      return $(el).text().trim();
    });
  }

  pressAltF() {
    let altFEvent = $.Event('keydown', { altKey: true, keyCode: 70 });
    $('body').trigger(altFEvent);
  }

  pressEsc() {
    let escEvent = $.Event('keydown', { keyCode: 27 });
    $('body').trigger(escEvent);
  }
}
