import { ref, onMounted, onUnmounted } from 'vue';
 

export const useMidlineMove = ({ containerQuery, leftQuery, moveCb }) => {
  const moveState = ref(false);
  const winW = ref(0);
  const leftMenuW = ref(0);
  const leftWidth = ref(50);
  const winResize = () => {
    winW.value = (
      document.querySelector(containerQuery) as HTMLElement
    ).offsetWidth;
    leftMenuW.value = (
      document.querySelector(leftQuery) as HTMLElement
    ).offsetWidth;
  };
  const midlineDown = () => {
    moveState.value = true;
  };
  const midlineUp = () => {
    moveState.value = false;
  };
  const midlineMove = e => {
    if (moveState.value) {
      let offset = e.x - leftMenuW.value;
      if (offset >= winW.value * 0.2 && offset <= winW.value * 0.8) {
        requestAnimationFrame(() => {
          leftWidth.value = parseFloat(
            ((offset / winW.value) * 100).toFixed(1)
          );
          moveCb && moveCb();
        });
      }
    }
  };
  onMounted(() => {
    console.log(
      document.querySelector(containerQuery),
      document.querySelector(leftQuery)
    );
    winW.value = (
      document.querySelector(containerQuery) as HTMLElement
    ).offsetWidth;
    leftMenuW.value = (
      document.querySelector(leftQuery) as HTMLElement
    ).offsetWidth;
    window.addEventListener("resize", winResize);
  });
  onUnmounted(() => {
    window.removeEventListener("resize", winResize);
  });
  return {
    moveState,
    leftMenuW,
    leftWidth,
    winResize,
    midlineDown,
    midlineUp,
    midlineMove
  };
};