import * as THREE from 'three';

import * as Types from "../../../../types/world/worldTypes";

function updateDistanceText(
    scene: THREE.Scene,
    floorPlanGroupLine: Types.RefGroup,
    affectedLines: Types.NumberArray
): void {

    //////////  Updating the Distance Texts of the lines that are affected during drag //////////

    const DistanceGroup = scene.children.find((child) => child.name === "Distance_Text") as THREE.Group;

    affectedLines.forEach((lineIndex) => {
        const mesh = floorPlanGroupLine.current.children[lineIndex] as THREE.Mesh;
        const linePoints = mesh.userData.linePoints;

        if (linePoints) {
            const distance = linePoints[0][0].distanceTo(linePoints[1][0]).toFixed(1);
            const position = new THREE.Vector3().addVectors(linePoints[0][0], linePoints[1][0]).divideScalar(2);

            if (!DistanceGroup || !linePoints) {
                return
            }

            DistanceGroup.children.forEach((text) => {
                const textMesh = text as THREE.Mesh;
                if (textMesh.userData[0][1] === linePoints[0][1] && textMesh.userData[1][1] === linePoints[1][1]) {
                    textMesh.position.set(position.x, 1, position.z);
                    const className = `Distance line-${textMesh.userData[0][1]}_${textMesh.userData[1][1]}_${linePoints[0][2]}`;
                    const element = document.getElementsByClassName(className)[0] as HTMLElement;
                    if (element) {
                        element.innerHTML = `${distance} m`;
                    }
                }
            });
        }
    });
}

export default updateDistanceText;
