import * as THREE from 'three';
import updateReferencePolesheight from './updateReferencePolesheight';

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

function addAndUpdateReferencePillar(
    raycaster: THREE.Raycaster,
    floorGroup: Types.RefGroup,
    referencePole: Types.RefMesh
): void {

    //////////  Find Pillars position and scale based on the pointer interaction  //////////

    let Roofs = raycaster.intersectObjects(floorGroup.current.children, true);
    const intersected = Roofs.find(intersect => intersect.object.name.includes("Roof") || intersect.object.name.includes("Floor"));

    if (intersected) {
        const intersectionPoint = intersected.point;
        raycaster.ray.origin.copy(intersectionPoint);
        raycaster.ray.direction.set(0, -1, 0);
        const belowIntersections = raycaster.intersectObjects(floorGroup.current.children, true);
        const validIntersections = belowIntersections.filter(intersect => intersect.object.name.includes("Floor"));

        let distance: Types.Number;

        if (validIntersections.length > 1) {
            let valid = validIntersections.find(intersectedBelow => intersected.point.distanceTo(intersectedBelow.point) > 3);
            if (valid) {
                updateReferencePolesheight(intersectionPoint, valid.distance, referencePole, floorGroup);
            } else {
                const belowPoint = new THREE.Vector3(intersectionPoint.x, 0, intersectionPoint.z);
                distance = intersected.point.distanceTo(belowPoint);
                if (distance > 3) {
                    updateReferencePolesheight(intersectionPoint, distance, referencePole, floorGroup);
                }
            }
        } else {
            const belowPoint = new THREE.Vector3(intersectionPoint.x, 0, intersectionPoint.z);
            distance = intersected.point.distanceTo(belowPoint);
            if (distance > 3) {
                updateReferencePolesheight(intersectionPoint, distance, referencePole, floorGroup);
            }
        }
    } else {
        if (referencePole.current) {
            (<any>referencePole.current.material).dispose();
            (<any>referencePole.current.geometry).dispose();
            floorGroup.current.remove(referencePole.current);
            referencePole.current = null;
        }
    }
}

export default addAndUpdateReferencePillar;
