import $ from "jquery";

class IHKNav {
  constructor(nav) {
    this.nav = nav.addClass('initiated');
    this.primary = nav.find('.primary');
    this.baseUrl = this.primary.attr('data-base-url');
    this.rootUrl = this.primary.attr('data-root-url');

    this.initPrimaryNav();
    this.initSecondaryNav();

    $('body').on('open-navigation', (event, data) => {
      this.initPrimaryNav(data.rootUrl);
    })
  }

  initPrimaryNav(optionalRootUrl) {
    this.primary.empty()

    if (optionalRootUrl) {
      this.rootUrl = optionalRootUrl;
      this.primary.off('click', 'a');
    }

    this.primary.append($('<ul class="current" />').attr('data-json', this.baseUrl + this.rootUrl));

    this.primary.on('click', 'a', (e) => {
      const a = $(e.currentTarget);
      const li = a.parent();
      const ul = li.parent('ul');

      if (li.hasClass('deep')) {
        e.preventDefault();

        if (a.siblings('ul').length) {
          ul.removeClass('current');
          this.toTop(ul);
          a.siblings('ul').addClass('current');
          li.addClass('open');
          this.manageTabIndex();
        } else {
          const deepUl = $('<ul />').attr('data-json', a.attr('href')).appendTo(li);
          this.loadNav(deepUl);
        }
      } else if (li.hasClass('back')) {
        e.preventDefault();
        this.toTop(ul);

        if (ul.closest('li').length) {
          ul.removeClass('current')
            .closest('li').removeClass('open')
            .parent('ul').addClass('current');
          this.manageTabIndex();
        } else {
          const backUl = $('<ul />').attr('data-json', a.attr('href')).insertBefore(ul);
          this.loadNav(backUl);
        }
      }
    });

    this.loadNav(this.nav.find('.primary ul'));
  }

  initSecondaryNav() {
    // secondary-nav-item
    const $secondary = this.nav.find(".secondary");
    const $secondaryItems = $secondary.find(".secondary-nav-item");
    $.each($secondaryItems, (index, element) => {
      $(element).on("click", (e) => {
        if ($(element).data("is-channel")) {
          e.preventDefault();
          const elementRootUrl= $(this).data("root-url");
          this.initPrimaryNav(elementRootUrl);
        } else {
          return true;
        }
      });
    });
  }

  loadNav(ul) {
    const currentPageId = this.nav.find('.primary').data("page-content-id");

    if (ul.parent('li').length) {
      ul.addClass('current');
      setTimeout(() => {
        const parentUl = ul.addClass('loading').parent('li').addClass('open')
          .closest('.current').removeClass('current');
        this.toTop(parentUl);
      }, 20)
    }

    $.ajax({
      url: ul.attr('data-json'),
      type: "GET",
      dataType: "json",
      xhrFields: {withCredentials: true}
    }).done((data) => {
      ul.attr('data-cm-metadata', '[{"_":{"$Ref":"content/' + data.tocListId + '"}}]');
      if (data.parentId) {
        $('<li class="back" />').appendTo(ul)
          .append($('<a />').attr('href', this.baseUrl + data.parentId).text(data.title));
      }
      if(!data.hideOverview) {
        if (data.showOverview) {
          const overviewElement = $('<li class="overview" />');
          overviewElement.appendTo(ul)
            .append($('<a />').attr('href', data.url).text(window.ihk.translations.overview));

          if (data.contentId === currentPageId.toString()) {
            overviewElement.find("a").addClass("active");
          }
        }
      }
      const parentElement = data;
      $.each(data.items, (index, item) => {
        const itemsBaseUrl = ihk.settings !== undefined ? ihk.settings.navigationItemsUrl : '';
        let itemUrl = item.url;
        if (itemsBaseUrl) {
          itemUrl = itemsBaseUrl + itemUrl;
        }

        let li = $('<li />').attr('data-id', item.contentId).attr('data-cm-metadata', '[{"_":{"$Ref":"content/' + item.contentId + '"}}]').appendTo(ul),
          a = $('<a />').html(item.title).appendTo(li);

        switch (item.type) {
          case "CMChannel" :
            li.addClass('deep');
            a.attr('href', this.baseUrl + item.contentId);
            break;
          case "CMArticle" :
            li.addClass('link');
            a.attr('href', itemUrl);
            break;
          default :
            li.addClass('miscellaneous');
            li.attr('data-type', item.type);
            a.attr('href', itemUrl);
        }

        if (item.linktype === 'external') {
          li.addClass('external');
          $(li).find("a").attr("target","_blank")
        }

        if (item.viewType === 'onlinemagazinstart') {
          // todo als link
          li.removeClass('deep');
          li.addClass('magazine-nav');
          $(li).find("a").attr("href",itemUrl);
          if (item.titleImage) {
            a.text('').append($('<img src="' + item.titleImage + '" alt="' + item.title + '" />'))
          }
        }
        if (item.viewType === 'themenseite' && !parentElement.root) {
          li.addClass('overview');
          li.removeClass('deep');
          a.attr('href', itemUrl);
        }

        if (item.trackCode && item.trackCode.length > 0) {
          $(li).find("a").attr("onmousedown", item.trackCode);
        }

        if (item.restrictedTo && item.restrictedTo.indexOf('extranet') > -1) {
          li.addClass('extranet');
        } else if (item.restrictedTo && item.restrictedTo.indexOf('intranet') > -1) {
          li.addClass('intranet');
        }

        if (item.doctype &&
          (item.doctype.indexOf('Datei') > -1 || item.doctype.indexOf('PDF') > -1 || item.doctype.indexOf('PIC') > -1)) {
          li.addClass('download');
        }

        if(item.contentId === currentPageId.toString()){
          $(li).find("a").addClass("active");
        }
      });

      ul.addClass('current').attr('data-id', data.contentId);

      if (ul.parent('li').length) {
        setTimeout( () => {
          const parentUl = ul.removeClass('loading').parent('li').addClass('open')
            .closest('.current').removeClass('current');
          this.toTop(parentUl);
          this.manageTabIndex();
        }, 20)
      } else if (ul.next('ul').length) {
        const innerUl = ul.next('ul');
        let wrapperLi = ul.find('li[data-id="' + innerUl.attr('data-id') + '"]').addClass('open');

        if (!wrapperLi.length) {
          wrapperLi = $('<li />').addClass('open').appendTo(ul);
        }

        wrapperLi.append(innerUl);

        setTimeout(() => {
          innerUl.removeClass('current');
          wrapperLi.removeClass('open');
          this.manageTabIndex();
        }, 20)
      }
    })
  }

  manageTabIndex() {
    this.nav.find('.primary a').attr('tabindex', '-1');
    this.nav.find('.primary .current > li > a').removeAttr('tabindex');
  }

  toTop(ul) {
    if (ul.scrollTop() > 0) {
      ul.animate({'scrollTop': 0}, 300, 'swing');
    }
  }
}

export default IHKNav;

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.page-header nav:not(.initiated)').each(function () {
    new IHKNav($(this));
  });
});
