const $ = require('jquery');
const Bloodhound = require("typeahead.js/dist/bloodhound.js");
const Typeahead = require("typeahead.js/dist/typeahead.jquery.js");
class Finder {
  constructor(section) {
    const t = this;
    this.serviceUrlBase = "/blueprint/servlet/serviceport/ihkfinder";
    this.ihklListUrl = 'services/ihkList.json';//this.serviceUrlBase + "/ihk/all";
    this.communitiesUrl = 'services/communities.json';//this.serviceUrlBase + "/community/all";

    // berechnen d
    // center ist geolocation aus js api
    // item die IHK
    /*
    const p = 0.017453292519943295;
    const c = Math.cos;
    const a = 0.5 - c((item.lat - center.lat) * p) / 2 + c(center.lat * p) * c(item.lat * p) * (1 - c((item.lng - center.lng) * p)) / 2;
    const distance = 12742 * Math.asin(Math.sqrt(a));
    */

    $(section).addClass("initialized");
    t.section = section;
    t.map = section.find('.map');
    t.form = section.find('.ihk-finder');
    t.charMap = {
      'a': /[àáâ]/gi,
      'c': /[ç]/gi,
      'e': /[èéêë]/gi,
      'i': /[ï]/gi,
      'o': /[ô]/gi,
      'oe': /[œ]/gi,
      'u': /[ü]/gi,
      's': /[ß]/gi
    };
    t.loadLocations();
  }
  loadLocations() {
    const t = this;
    $('.page-header .toggle-ihk-list').on('click', function (e) {
      e.preventDefault();
      $('.page-header').toggleClass('nav-open');
    });
    t.mapBox = {
      top: 55.1,
      right: 15.2,
      bottom: 47.1,
      left: 5.8
    };
    t.indexLetter = "";
    t.ihkIndex = $('<ul class="ihk-index" />').appendTo($('.page-header .ihk-list'));
    $.getJSON(this.ihklListUrl, function (response) {
      if (response.jsonResponse && response.status === 200) {
        t.ihkList = response.jsonResponse.sort((a, b) => {
          const countryNameA = a.country.toUpperCase(); // ignore upper and lowercase
          const countryNameB = b.country.toUpperCase(); // ignore upper and lowercase
          // Sort by country
          if (countryNameA < countryNameB) {
            return -1;
          }
          if (countryNameA > countryNameB) {
            return 1;
          }
          const ihkNameA = a.name.toUpperCase(); // ignore upper and lowercase
          const ihkNameB = b.name.toUpperCase(); // ignore upper and lowercase
          // Sort by name
          if (ihkNameA < ihkNameB) {
            return -1;
          }
          if (ihkNameA > ihkNameB) {
            return 1;
          }
          // names must be equal
          return 0;
        });
        $.each(response.jsonResponse, function () {
          t.setMarker(this);
          t.buildListItem(this);
        });
        t.initForm();
      }
    })
  }
  /*
  buildListItem(json) {
    const t = this;
    const li = $('<li />').appendTo(t.ihkIndex);
    //todo urls
    // $('<a />').attr('data-ihknr', json.ihknr).text(json.name).attr('href', json.link[0].url).appendTo(li);
    $('<a />').attr('data-ihknr', json.ihknr).text(json.name).appendTo(li);
    if (t.indexLetter != json.country) {
      t.indexLetter = json.country;
      li.prepend($('<span class="index-letter" />').text(t.indexLetter));
    }
  }
  */

  buildListItem(json) {
    const t = this;
    //todo urls, API muss noch erweitert
    // $('<a />').attr('data-ihknr', json.ihknr).text(json.name).attr('href', json.link[0].url).appendTo(li);

    // generiere parent Element, Bundesland
    if (t.indexLetter !== json.country) {
      const parentLi = $('<li />');
      const itemLi = $('<li />');
      const ul =$('<ul />').appendTo(parentLi);

      t.indexLetter = json.country;
      const a = $('<a />').attr('data-ihknr', json.ihknr).text(json.name).appendTo(itemLi);
      parentLi.addClass("with-index");
      parentLi.prepend($('<span class="index-letter" />').text(t.indexLetter));
      itemLi.appendTo(ul);
      parentLi.appendTo(t.ihkIndex);
    }
    // Generiere einzelne IHKS
    else {
      const liSecond = $('<li />');
      const parentIndex = $(t.ihkIndex).find(".with-index").last().find("ul");
      const a = $('<a />').attr('data-ihknr', json.ihknr).text(json.name).appendTo(liSecond);
      liSecond.appendTo(parentIndex);
    }
  }

  setMarker(json) {
    const t = this;
    const marker = $('<div class="marker" id="ihk-' + json.ihknr + '" data-title="' + json.key + '" />');
    const opener = $('<a href="tooltip_' + json.ihknr + '" tabindex="-1" />').appendTo(marker);
    const tooltip = $('<div class="tooltip" id="tooltip_' + json.ihknr + '" />').appendTo(marker);
    const contents = $('<div class="contents" />');
    // const name = json.name.replace('Industrie- und Handelskammer', 'IHK');
    const name = json.longname;
    const closer = $('<button class="closer" tabindex="-1" />');
    tooltip.append($('<p class="title" />').text(name));
    tooltip.append(closer);
    tooltip.append(contents);
    if (name.length > 65) {
      tooltip.addClass('extra-long-name');
    }
    else if (name.length > 40) {
      tooltip.addClass('long-name');
    }
    contents.append($('<p class="details" />').html(json.street + '<br>' + json.zip + ' ' + json.city));
    //todo url nachtragen
    // contents.append($('<a class="btn has-icon icon-pfeil-rechts" tabindex="-1" data-ihknr="' + json.ihknr +'" />').attr('href', json.link[0].url).text('Zu Ihrer IHK'));
    contents.append($('<a class="btn has-icon icon-pfeil-rechts" tabindex="-1" data-ihknr="' + json.ihknr + '" />').text('Zu Ihrer IHK'));
    marker.css({
      'left': Math.round((json.geodata.latitude - t.mapBox.left) / (t.mapBox.right - t.mapBox.left) * 10000) / 100 + '%',
      'top': Math.round((json.geodata.longitude - t.mapBox.top) / (t.mapBox.bottom - t.mapBox.top) * 10000) / 100 + '%'
    });
    t.map.append(marker);
    opener.on('click', (e) => {
      e.preventDefault();
      const marker = $(e.currentTarget).closest('.marker');
      if (marker.hasClass('open')) {
        marker.removeClass('open');
      }
      else {
        this.openMarker(marker);
      }
    });
    closer.on('click', function (e) {
      const marker = $(this).closest('.marker').removeClass('open');
      t.setMarkerTabindex(marker);
    });
    marker.find('.btn').on('click', function (e) {
      e.preventDefault();
      t.navigateTo($(this));
    })
  }
  openMarker(marker) {
    marker.addClass('open');
    const prevMarker = marker.siblings('.open');
    const tooltip = marker.find('.tooltip');
    let maxOffset = 280;
    if (tooltip.hasClass('long-name')) {
      maxOffset = 310;
    }
    if (tooltip.hasClass('extra-long-name')) {
      maxOffset = 340;
    }
    if (marker.offset().top < maxOffset) {
      marker.addClass('sideways');
    }
    else {
      marker.removeClass('sideways');
    }
    this.setMarkerTabindex(marker);
    if (prevMarker.length) {
      prevMarker.removeClass('open');
      this.setMarkerTabindex(prevMarker);
    }
  }
  initForm() {
    const t = this;
    $.getJSON(this.communitiesUrl, function (response) {
      if (response.jsonResponse && response.status === 200) {
        t.communities = response.jsonResponse;
        t.initBloodhound(t.communities);
      }
      t.form.on('submit', function () {
        if ($('.tt-cursor').length) {
          $('.tt-cursor').trigger('click');
        } else if ($('.tt-suggestion').length > 1) {
          $('.tt-suggestion').first().trigger('click');
        }
        return false;
      });
    });
  }
  initBloodhound(data) {
    const t = this;
    $.each(data, function (index, value) {
      data[index]['normName'] = t.normalize(data[index].name);
    });
    data.sort(function (a, b) {
      if (a.name < b.name) return -1;
      if (a.name > b.name) return 1;
      return 0;
    });
    t.communities = new Bloodhound({
      datumTokenizer: function (d) {
        var titleTokens = Bloodhound.tokenizers.whitespace(d.normName);
        return titleTokens.concat(d.zips)
      },
      queryTokenizer: function (q) {
        var normalized = t.normalize(q);
        return Bloodhound.tokenizers.whitespace(normalized);
      },
      local: data,
      limit: 50
    });
    t.communities.initialize();
    var src = {
      name: 'communities',
      displayKey: 'name',
      source: t.communities.ttAdapter(),
      templates: {
        empty: ['<p class="no-result">Leider nichts gefunden</p>'].join('\n'),
        suggestion: function (e) {
          return ('<div data-id="' + e.ihknr + '" ><span class="name">' + e.name + '</span/><span class="zip">' + (e.zips ? e.zips.join(', ') : ' ') + '</span></div>');
        }
      }
    }
    t.initTypeahead(src);
  }
  initTypeahead(source) {
    const t = this;
    const input = t.form.find('input[type="text"]');
    input.typeahead({
        highlight: true,
        ttl_ms: 0
      },
      source
    );
    input.bind('typeahead:selected', (e, item, sourceName) => {
      const marker = $('.marker#ihk-' + item.ihknr);
      this.openMarker(marker);
      const prevMarker = marker.siblings('.open').removeClass('open');
      marker.siblings().removeClass('hover');
      t.setMarkerTabindex(marker);
      if (prevMarker.length) {
        t.setMarkerTabindex(prevMarker);
      }
    });
    input.bind('typeahead:autocompleted', function (e, item) {
      //console.log(item);
    })
    t.form.on('mouseenter', '.tt-suggestion', function () {
      $('.marker#ihk-' + $(this).attr('data-id')).addClass('hover').siblings('hover').removeClass('hover');
    })
    t.form.on('mouseleave', '.tt-suggestion', function () {
      $('.marker#ihk-' + $(this).attr('data-id')).removeClass('hover');
    })
    t.form.on('keyup', function () {
      if (t.form.find('.tt-cursor').length) {
        $('.marker#ihk-' + t.form.find('.tt-cursor').attr('data-id')).addClass('hover').siblings('.hover').removeClass('hover');
        const openMarker = $('.marker.open').removeClass('open');
        if (openMarker.length) {
          t.setMarkerTabindex(openMarker);
        }
      } else {
        $('.marker.hover').removeClass('hover');
      }
    })
  }
  setMarkerTabindex(marker) {
    const t = this;
    if (marker.hasClass('open')) {
      marker.find('.tooltip a, .tooltip button').removeAttr('tabindex');
      marker.find('.btn').focus();
      marker.removeClass('hover').siblings('.hover').removeClass('hover');
      if (!marker.is(':visible')) {
        t.navigateTo(marker.find('.btn'));
      }
    } else {
      marker.find('.tooltip a, .tooltip button').attr('tabindex', '-1');
    }
  }
  navigateTo(link) {
    console.log('SET COOKIE: ' + link.attr('data-ihknr'));
    window.location = link.attr('href');
  }
  normalize(str) {
    const t = this;
    $.each(t.charMap, function (normalized, regex) {
      str = str.replace(regex, normalized);
    });
    return str;
  }
}
$(document).ready(function () {
  $('.ihk-selection:not(.initialized)').each(function (i) {
    new Finder($(this));
  });
});
