// import $ from 'jquery';
import Slider from './slider';
import Masonry from "./masonry";

const $ = require('jquery');

class Gallery {
  constructor(section) {
    this.section = section.addClass('initiated');
    this.wrapper = section.find('.gallery-wrapper');
    this.items = this.wrapper.children('.image');
    this.gridInitialized = false;
    this.currentPage = -1;
    this.visibleItems = [];
    this.type = section.attr('data-type');
    this.initPopup();

    if (this.type === 'first-image' || this.type === 'single-image') {
      this.initSingleThumb();
    } else if (this.type === 'grid') {
      this.initThumbs();
      this.initLoading();
    } else if (this.type === 'masonry') {
      this.initMasonry();
    }

    this.initScrollCheck();
    $('body').on('lazyload-gallery-image', () => {
      this.lazyLoadSingleImages.call(this);
    })
  }

  initScrollCheck() {
    window.addEventListener("scroll", () => {
      window.requestAnimationFrame(() => {
        this.scrollCheck();
      })
    }, {passive: true});

    this.scrollCheck();
  }

  scrollCheck() {
    const w = $(window);

    if (this.type === 'first-image' || this.type === 'single-image') {
      if (!this.isLoaded && w.scrollTop() + w.height() + 100 > this.section.offset().top) {
        const thumb = this.items.first();
        thumb.find('img').attr('src', thumb.data(this.type === 'first-image' ? 'thumb' : 'full'));
        this.isLoaded = true;
      }
    } else if (this.type === 'grid') {
      if (!this.gridInitialized && this.items.length > this.visibleItems.length && w.scrollTop() + w.height() + 300 > ($(this.section).offset().top + $(this.section).height())) {
        this.currentPage++;
        this.loadThumbs();
        this.gridInitialized = true;
      }
    }
  }

  lazyLoadSingleImages() {
    if (this.type === 'first-image' || this.type === 'single-image') {
      if (!this.isLoaded) {
        const thumb = this.items.first();
        thumb.find('img').attr('src', thumb.data(this.type === 'first-image' ? 'thumb' : 'full'));
        this.isLoaded = true;
      }
    }
  }

  initSingleThumb() {
    const first = this.items.first();
    const a = $('<a href="' + first.data('full') + '" />').attr('data-index', 0).appendTo(first);
    const img = $('<img alt="' + first.attr("alt") + '" />').appendTo(a);

    first.find('.image-description').appendTo(this.wrapper);

    this.isLoaded = false;

    img.one('load', () => {
      this.section.addClass('loaded');
    });

    if (this.items.length > 1) {
      a.append($('<span class="btn has-icon icon-galerie" />').text(this.items.length + ' Bilder'));
      first.find('.image-description').hide();
    }

    if (this.section.data('type') === 'single-image') {
      const ratio = (Math.round(first.data('height') / first.data('width') * 1000) / 10) + '%';
      a.css('padding-top', ratio);
      first.find('.copyright').appendTo(a).css('max-width', ratio);
    }

    this.section.closest('.main-col').addClass('clearfix');
  }

  initThumbs() {
    this.items.each(function (i) {
      const item = $(this);
      $('<a href="' + item.data('full') + '" />').attr('data-index', i).appendTo(item);
    })
  }

  initMasonry() {
    this.items.each(function (i) {
      const item = $(this);
      const a = $('<a href="' + item.data('full') + '" />').attr('data-index', i).appendTo(item);

      a.css('padding-top', Math.round(item.data('height') / item.data('width') * 10000) / 100 + '%');
    })

    const btnText = window.ihk.translations.loadMoreImages;
    new Masonry(this.wrapper, btnText, [
      {minWidth: 0, batchSize: 6},
      {minWidth: 0, batchSize: 6},
      {minWidth: 567, batchSize: 9},
      {minWidth: 1000, batchSize: 12}
    ]);
  }

  initLoading() {
    const imagesPerPage = this.section.data('per-page');
    const buttonWrapper = $('<div class="button-wrapper" />').appendTo(this.section);
    const buttonText = window.ihk.translations.loadMoreImages;
    if (this.items.length > imagesPerPage) {
      this.moreButton = $('<a href="#" class="btn load-more has-icon icon-laden icon-reload" />').text(buttonText).appendTo(buttonWrapper);
    }

    if (this.moreButton) {
      this.moreButton.on('click', (e) => {
        e.preventDefault();
        this.currentPage++;
        this.loadThumbs();
      })
    }

  }

  initTabIndex() {
    const focusable = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]';
    const unfocusable = '[tabindex=-1], [disabled], :hidden';
    const prevFocusable = this.section.prevAll().find(focusable).not(unfocusable).last();
    const nextFocusable = this.section.nextAll().find(focusable).not(unfocusable).first();

    this.items.find('a').focus((e) => {
      const focusElement = $(e.currentTarget);
      const currentIndex = parseInt(focusElement.attr('data-index'));

      prevFocusable.attr('tabindex', 1);
      this.items.eq(currentIndex - 1).find('a').attr('tabindex', 2);
      focusElement.attr('tabindex', 3);
      this.items.eq(currentIndex + 1).find('a').attr('tabindex', 4);
      nextFocusable.attr('tabindex', 5);
    })

    this.items.find('a').on('focusout', () => {
      this.items.find('a').removeAttr('tabindex');
      prevFocusable.removeAttr('tabindex');
      nextFocusable.removeAttr('tabindex');
    })

    nextFocusable.focus(() => {
      this.items.find('a').attr('tabindex', -1);
      this.visibleItems[this.visibleItems.length - 1].find('a').attr('tabindex', 0);
    })
  }

  loadThumbs() {
    const pp = this.section.data('per-page');
    const first = this.currentPage * pp;
    const last = first + pp < this.items.length ? first + pp : this.items.length;
    //const newItems = [];

    for (let i = first; i < last; i++) {
      const item = this.items.eq(i).addClass('loading');
      const img = $('<img />').one('load', function () {
        item.removeClass('loading').addClass('loaded');
      });
      img.attr('src', (this.section.data('type') === 'masonry' ? item.data('full') : item.data('thumb'))).appendTo(item.find('a'));
      img.attr('alt', item.attr('alt')).attr('title', item.attr("title")).appendTo(item.find('a'));
      this.visibleItems.push(item);
      //newItems.push(item);
    }
    if ( this.moreButton && last == this.items.length) {
      this.moreButton.hide();
    }

    /*
    if (this.cols) {
      this.addToCols(newItems);
    }
    */
  }

  /*
  handleResize() {
    this.width = this.section.outerWidth();
    this.timer = null;

    $(window).on('resize', () => {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      setTimeout(() => {
        this.resetCols();
      },200);
    })
  }

  resetCols() {
    const w = this.section.width();

    let cols = 2;
    if (w > 500) { cols = 3 }
    if (w > 1000) { cols = 4 }

    if (this.cols && cols === this.cols.length) {
      return;
    }

    $.each(this.cols, function () {
      this.col.remove();
    })

    this.cols = [];
    this.section.attr('data-cols', cols);

    for (let i = 0; i < cols; i++) {
      const col = $('<div class="column" />').appendTo(this.wrapper);

      this.cols.push({
        col: col,
        index: i,
        height: 0
      })
    }

    this.addToCols(this.visibleItems);
  }

  addToCols(items) {
    $.each(items, (i, element) => {
      const item = $(element);
      this.cols[0].col.append(item);
      this.cols[0].height = Math.round(item.position().top + item.outerHeight());
      this.cols.sort( this.compareCols );
    })
  }

  compareCols(a, b) {
    if (a.height < b.height) {
      return -1;
    }
    else if (a.height > b.height) {
      return 1;
    }
    else {
      if (a.index < b.index) {
        return -1;
      }
      if (a.index > b.index) {
        return 1;
      }
    }
    return 0;
  }
  */
  initPopup() {
    this.popup = $('<div class="gallery-popup" tabindex="-1" />').appendTo($('body'));

    const slides = $('<div class="slider" />').appendTo(this.popup);
    const closer = $('<button class="closer" />').prependTo(this.popup);

    if (this.items.length === 1) {
      slides.addClass('single-slide');
    }

    this.items.each((i, element) => {
      const item = $(element);
      const slide = $('<div class="slide preload" />').appendTo(slides);

      const imgElement = $('<div class="image-box" />').attr('data-src', item.data('full')).attr("title", item.attr("title"));

      if (this.section.data("render-download") === true) {
        imgElement.attr('data-download', item.data('download'));
      }
      imgElement.appendTo(slide);

      if (item.find('span').length > 0) {
        $('<div class="text-box" />').appendTo(slide).append(item.find('span').clone());
      }
    })

    closer.on('click', (e) => {
      e.preventDefault();
      this.popup.removeClass('open');
      this.popup.find('button, a').attr('tabindex', -1);
      this.unbindPopupKeys();
      this.toggleContentScroll();
    })

    this.slider = new Slider(slides);
    this.popup.find('button, a').attr('tabindex', -1);

    this.wrapper.on('click', 'a', (e) => {
      e.preventDefault();
      const index = parseInt($(e.currentTarget).attr('data-index'));
      this.popup.addClass('open');
      this.bindPopupKeys();
      this.popup.find('button, a').attr('tabindex', 0);
      this.popup.focus();
      this.slider.goTo(index, false);
      this.toggleContentScroll();
    });

    if (this.section.data('render-download')) {
      const download = $('<a href="#" download class="download" />').prependTo(this.popup);
      $(download).attr('href', this.slider.slides.eq(this.slider.currentSlide).find('.image-box').attr('data-download'));
    }

    slides.on('slide-change', () => {
      this.slider.loadImage();
      const download = this.popup.find(".download");
      if (download.length) {
        $(download).attr('href', this.slider.slides.eq(this.slider.currentSlide).find('.image-box').attr('data-download'));
      }
    })
  }


  bindPopupKeys() {
    $('body').on('keydown.gallery', (e) => {
      if (e.keyCode === 27) {
        this.popup.find('.closer').trigger('click');
      } else if (e.keyCode === 37) {
        this.slider.onPrev();
      } else if (e.keyCode === 39) {
        this.slider.onNext();
      }
    })
  }

  unbindPopupKeys() {
    $('body').off('keydown.gallery');
  }

  toggleContentScroll() {
    const body = $('body');
    const win = $(window);

    if (this.popup.hasClass('open')) {
      body.css('top', (win.scrollTop() * -1) + 'px').addClass('nav-open');
    } else {
      const top = Math.abs(parseInt(body.css('top')));
      body.removeClass('nav-open').removeAttr('style');
      win.scrollTop(top);
    }
  }
}

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