import { getData } from "../Popper.manage";
export default function handleOpenPopupPositionChange() {
  let popups = getData() || [];
  popups.forEach(popup => {
    if (popup.isPopupOpen) {
      const {
        placeHolderElement,
        dropElement,
        defaultPosition
      } = popup;
      const {
        position,
        positionsOffset = {}
      } = popup.state;

      if (placeHolderElement && dropElement) {
        const scrollContainer = placeHolderElement.closest("[data-scroll=true]") || document.body;
        requestAnimationFrame(() => {
          const needArrow = getNeedArrow(popup);
          const isAbsolute = getIsAbsolutePopup(popup);
          const customOrder = getCustomPositionOrder(popup);
          const betterPosition = viewPort.betterView(dropElement, placeHolderElement, defaultPosition, scrollContainer, {
            needArrow,
            isAbsolute,
            customOrder
          });
          const {
            view,
            views,
            viewsOffset = {},
            targetOffset,
            popupOffset
          } = betterPosition || {};
          const {
            left: oldLeft = "",
            top: oldTop = ""
          } = positionsOffset[position] || {};
          const {
            left = "",
            top = ""
          } = viewsOffset[view] || {};
          const changeState = isAbsolute ? position !== view : oldLeft !== left || oldTop !== top;

          if (changeState) {
            popup.methods.onPosition(view);
            popup.methods.onPositions(views);
            popup.methods.onPositionsOffset(viewsOffset);
            popup.methods.onTargetOffset(targetOffset);
            popup.methods.onPopupOffset(popupOffset);
            popup.methods.onIsAbsolutePositioningNeeded(isAbsolute);
          }
        });
      }
    }
  });
}