const $ = require('jquery');

class IHKSearchTypeahead {
  constructor(input) {
    this.input = input;
    this.api = input.data('api');
    this.tileWrapper = input.closest('form').next('.tiles');
    this.allResults = $('<a href="#" class="btn has-icon icon-small-arrow-right-simple" />').text('Alle Suchergebnisse');
    this.buttonWrapper = $('<span class="all-button-wrapper" />').append(this.allResults);
    this.resultCount = $('<span class="count" />').appendTo(this.allResults);

    //$('.results-wrapper').find('.h-kicker').each(function(i) {if (i < 10) {console.log($(this).text())}});
    this.handleKeyEvents();
  }

  handleKeyEvents() {
    this.input.on('input', () => {
      if (this.input.val().length > 0) {
        this.loadData(this.input.val().toLowerCase());
      }
    })
  }

  loadData(val) {
    fetch(this.api.replace('{SEARCHTERM}', val))
      .then(response => response.json())
      .then(response => {
        this.buildResults(response);
      });
  }

  buildResults(json) {
    let max = 6;

    if (json.results.count > 0) {
      this.tileWrapper.html('');
    }
    if (json.downloads.count > 0) {
      this.buildGroup(json.downloads, 'downloads', 'Downloads');
      max = max - 1;
    }
    if (json.events.count > 0) {
      this.buildGroup(json.events, 'events', 'Veranstaltungen');
      max = max - 1;
    }
    if (json['a-z'].count > 0) {
      this.buildGroup(json['a-z'], 'a-z', 'IHK von A bis Z');
      max = max - 1;
    }
    if (json['contacts'].count > 0) {
      this.buildGroup(json['contacts'], 'contacts', 'Ansprechpartner');
      max = max - 1;
    }

    json.results.items.map((result, i) => {
      if (i < max) {
        this.buildResult(result);
      }
    })

    if (json.proposals.count > 0) {
      this.buildProposals(json.proposals);
    }

    this.tileWrapper.append(this.buttonWrapper);
    this.resultCount.text(json.results.count);
  }

  buildResult(json) {
    const tile = $('<div/>').addClass('tile').appendTo(this.tileWrapper);
    const a = $('<a/>').attr('href', json.url).appendTo(tile);
    const inner = $('<span/>').addClass('inner').appendTo(a);
    const title = $('<span/>').addClass('item-title').appendTo(inner);
    title.text(this.cropTitle(json.title, json.kicker.length > 0));
    if (json.kicker.length > 0) {
      $('<span/>').addClass('kicker').text(json.kicker).prependTo(inner);
    }
    if (json.type.length > 0) {
      tile.attr('data-type', json.type);
    }
  }

  cropTitle(title, hasKicker) {
    const max = hasKicker ? 60 : 80;
    if (title.length > max) {
      return title.substr(0, max) + '…';
    } else {
      return title;
    }
  }

  buildGroup(json, tileClass, title) {
    const tile = $('<div/>').addClass('tile').addClass(tileClass).appendTo(this.tileWrapper);
    const outer = $('<div/>').addClass('outer').appendTo(tile);
    const inner = $('<div/>').addClass('inner').appendTo(outer);
    const p = $('<p/>').appendTo(inner);
    const ul = $('<ul/>').appendTo(inner);

    $('<a/>').attr('href', json.url).text(title + ' (' + json.count + ')').appendTo(p);

    json.items.map((item, i) => {
      if (i < 2) {
        const li = $('<li/>').appendTo(ul);
        $('<a/>').attr('title', item.title).attr('href', item.url).text(item.title.length > 48 ? item.title.substr(0, 48) + '…' : item.title).appendTo(li);
      }
    })
  }

  buildProposals(json) {
    this.tileWrapper.find('.proposals').remove();

    const proposals = $('<div/>').addClass('proposals').appendTo(this.tileWrapper);
    const p = $('<p/>').text('Meinten Sie vielleicht: ').appendTo(proposals);

    json.items.map((item) => {
      const a = $('<a/>').attr('href', item.url).text(item.title);
      p.append(a);
    })
  }
}

export default IHKSearchTypeahead;

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.search-field.typeahead:not(.initiated)').each(function () {
    new IHKSearchTypeahead($(this));
  })
})
