export default {
  inserted(el, bindings, { context }) {
    if (context.appendToBody) {
      let {
        height,
        top,
        left,
        width,
      } = context.$refs.toggle.getBoundingClientRect();

      const { calculatePosition } = context;
      const rootEl = el.closest('.itf-append-context') || document.body;
      if (rootEl) {
        let {
          top: parentTop,
          left: parentLeft
        } = rootEl.getBoundingClientRect();
        left -= parentLeft + rootEl.scrollLeft;
        top -= parentTop + rootEl.scrollTop;
      } else {
        let scrollX = window.scrollX || window.pageXOffset
        let scrollY = window.scrollY || window.pageYOffset

        left += scrollX;
        top += scrollY;
      }

      if (calculatePosition) {
        el.unbindPosition = calculatePosition(el, context, {
          width: width + 'px',
          left: left + 'px',
          top: (top + height) + 'px',
          root: rootEl
        });
      }

      (rootEl || document.body).appendChild(el)
    }
  },

  unbind(el, bindings, { context }) {
    if (context.appendToBody) {
      if (el.unbindPosition && typeof el.unbindPosition === 'function') {
        el.unbindPosition()
      }
      if (el.parentNode) {
        el.parentNode.removeChild(el)
      }
    }
  },
}
