import { useStage } from "@/core/hook/use-global-vars";
import { Text } from "konva/lib/shapes/Text";

export const useGetPointerTextNdx = () => {
  const stage = useStage();

  return (shape: Text) => {
    let pointerPos = stage.value?.getNode().pointerPos;
    const str = shape.text();
    if (!pointerPos || str.length === 0) {
      return str.length;
    }

    const transform = shape.getAbsoluteTransform().copy().invert()
    const textPos = {x: 0, y: 0}
    const finalPos = transform.point({
      x: pointerPos.x - textPos.x,
      y: pointerPos.y - textPos.y,
    });

    const width = shape.width();
    const textHeight = shape.textHeight;
    const lineNdx = Math.floor(finalPos.y / textHeight);
    const textArr = shape.textArr;
    let ndx = str.length;

    if (lineNdx >= textArr.length || lineNdx < 0) return ndx;

    const line = textArr[lineNdx];
    const hanlfSize = shape.fontSize() / 2
    let i = 0;
    let x = 0;
    if (shape.align() === 'center') {
      x = (width - line.width) / 2;
    } else if (shape.align() === 'right') {
      x = width - line.width;
    }

    let after = false;
    for (; i < line.text.length; i++) {
      const size = shape.measureSize(line.text[i]);
      x += size.width;
      if (x > finalPos.x) {
        const diff = x - finalPos.x
        if (diff < hanlfSize && line.text.length >= i + 1) {
          after = true;
        }
        break;
      }
    }
    if (i === line.text.length) {
      ndx = line.text.length - 1;
      after = true;
    } else {
      ndx = i;
    }

    let strNdx = 0;
    let emptyCount = 0;
    for (let i = 0; i < lineNdx; i++) {
      const cStr = textArr[i].text;
      if (!cStr) {
        // emptyCount++;
      } else if (i !== lineNdx) {
        strNdx = strNdx + str.substring(strNdx).indexOf(cStr) + cStr.length;
        emptyCount = 0;
      } else {
        strNdx = strNdx + str.substring(strNdx).indexOf(cStr);
        emptyCount = 0;
      }
      if (i !== lineNdx) {
        if (textArr[i].lastInParagraph) {
          strNdx += 1;
        }
      }
    }

    const char = line.text[ndx];
    const yStr = str.substring(strNdx + emptyCount);
    i = ndx;
    for (; i < yStr.length; i++) {
      if (yStr[i] === char) {
        break;
      }
    }
    ndx = strNdx + emptyCount + i + (after ? 1 : 0);
    return ndx;
  };
};
