import { on, off, elem } from '../helpers/dom';
import '../assets/scss/directives/loading.scss';

export default {
  handleShow(el, modifiers) {
    el.classList.add('itf-loading-wrapper');
    let loader = el.getElementsByClassName('itf-loading');
    if (!loader.length) {
      loader = elem('div', 'itf-loading itf-loading-default');
      const message = elem('div', 'itf-loading-message text-center');
      const icon = elem('span', 'itf-loading-icon');
      const loadingText = elem('span', 'itf-loading-text');
      message.appendChild(icon);
      message.appendChild(loadingText);
      loader.appendChild(message);
      el.appendChild(loader);
    }

    if (modifiers.centered && typeof window !== 'undefined') {
      el.resizeHandler = () => scrolling();

      on(window, 'scroll', el.resizeHandler);
      on(window, 'resize', el.resizeHandler);

      scrolling();
    }

    function scrolling() {
      var imgHeight = 32,
        rect = el.getBoundingClientRect(),
        scrollTop = window.scrollY,
        scrollBot = scrollTop + window.innerHeight,
        elTop = rect.top + ( window.pageYOffset || document.body.scrollTop ) - ( document.body.clientTop || 0 ),
        elBottom = elTop + rect.height,
        visibleTop = elTop < scrollTop ? scrollTop : elTop,
        visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;

      var chBottom = visibleBottom - elBottom,
        chTop = visibleTop - elTop,
        imgTop = Math.floor((rect.height + chBottom + chTop - imgHeight) / 2);

      message.style.top = imgTop + 'px';
    }
  },
  handleHide(el, modifiers) {
    el.classList.remove('itf-loading-wrapper');

    if (modifiers.centered && typeof window !== 'undefined') {
      off(window, 'scroll', el.resizeHandler);
      off(window, 'resize', el.resizeHandler);
    }

    // const blockers = el.getElementsByClassName('itf-loading');
    // for (const blocker of blockers) {
    //   blocker.remove();
    // }
  },
  bind(el, { value, modifiers, def }) {
    def.handleHide(el, modifiers);
    if (value) {
      def.handleShow(el, modifiers);
    }
  },
  unbind(el, { value }) {
  },
  update (el, { value, modifiers, def }) {
    def.handleHide(el, modifiers);
    if (value) {
      def.handleShow(el, modifiers);
    }
  }
};
