import { onMounted, onUnmounted, watchEffect } from "vue";

export function dragSplitPane() {
  let pos = { y: 0 };
  const dragSpliter = $ref<HTMLDivElement>();
  let areaHeight = $ref(0);
  let initAreaHeight = 0;
  const minAreaHeight = 74;
  let maxAreaHeight = null;

  const mouseDownHandler = function (e: MouseEvent) {
    // console.log(e);
    if (e.target !== dragSpliter) return;
    e.preventDefault();
    pos = {
      y: e.clientY,
    };

    const parentDom = dragSpliter.parentElement.parentElement;
    let sumHeight = 0;
    for (let i = 0; i < parentDom.childNodes.length; i++) {
      const dom = parentDom.childNodes[i];
      if (
        dom.className &&
        !dom.className.includes("board-questions") &&
        !dom.className.includes("board-footer")
      ) {
        sumHeight += dom.offsetHeight;
      }
    }
    maxAreaHeight = parentDom.offsetHeight - sumHeight - 16 * 4 - 68;
    initAreaHeight =
      dragSpliter.parentElement.previousElementSibling.offsetHeight;
    if (dragSpliter) {
      document.addEventListener("mousemove", mouseMoveHandler);
      document.addEventListener("mouseup", mouseUpHandler);
    }
    return false;
  };

  const mouseMoveHandler = function (e: MouseEvent) {
    e.preventDefault();
    const dy = e.clientY - pos.y;
    const curHeight = initAreaHeight + dy;
    areaHeight = Math.min(maxAreaHeight, Math.max(curHeight, minAreaHeight));

    return false;
  };

  const mouseUpHandler = function () {
    if (dragSpliter) {
      document.removeEventListener("mousemove", mouseMoveHandler);
      document.removeEventListener("mouseup", mouseUpHandler);
    }
  };

  onMounted(() => {
    watchEffect(() => {
      if (dragSpliter) {
        document.addEventListener("mousedown", mouseDownHandler);
      }
    });
  });
  onUnmounted(() => {
    if (dragSpliter) {
      document.removeEventListener("mousedown", mouseDownHandler);
      document.removeEventListener("mousemove", mouseMoveHandler);
      document.removeEventListener("mouseup", mouseUpHandler);
    }
  });

  return $$({ dragSpliter, areaHeight });
}
