import * as THREE from 'three';

const calculateAssetTransformationOnWall = (
    asset: WallAsset,
    initialWall: Wall,
    newWall: Wall
): { position: [number, number, number], rotation: [number, number, number] } => {
    const [initialStartPoint, initialEndPoint] = initialWall.points;
    const [newStartPoint, newEndPoint] = newWall.points;

    const initialWallVector = new THREE.Vector3(initialEndPoint.position[0] - initialStartPoint.position[0], 0, initialEndPoint.position[2] - initialStartPoint.position[2]);

    const assetVector = new THREE.Vector3(asset.position[0] - initialStartPoint.position[0], 0, asset.position[2] - initialStartPoint.position[2]);

    const initialWallLength = initialWallVector.length();
    const initialWallNormalized = initialWallVector.normalize();
    const dotProduct = assetVector.dot(initialWallNormalized);

    const projection = initialWallNormalized.clone().multiplyScalar(dotProduct);
    const perpendicular = new THREE.Vector3().subVectors(assetVector, projection);
    const distanceFromWall = perpendicular.length();

    const crossProduct = new THREE.Vector3().crossVectors(initialWallNormalized, perpendicular).y;
    const signedDistance = distanceFromWall * (crossProduct >= 0 ? 1 : -1);

    const percentage = Math.max(0, Math.min(1, dotProduct / initialWallLength));

    const newWallVector = new THREE.Vector3(newEndPoint.position[0] - newStartPoint.position[0], 0, newEndPoint.position[2] - newStartPoint.position[2]);

    const x = newStartPoint.position[0] + (newEndPoint.position[0] - newStartPoint.position[0]) * percentage;
    const z = newStartPoint.position[2] + (newEndPoint.position[2] - newStartPoint.position[2]) * percentage;

    const newWallNormal = new THREE.Vector3(-newWallVector.z, 0, newWallVector.x).normalize();

    const offsetX = newWallNormal.x * signedDistance;
    const offsetZ = newWallNormal.z * signedDistance;

    const wallAngle = Math.atan2(newWallVector.z, newWallVector.x);

    return {
        position: [x + offsetX, asset.position[1], z + offsetZ],
        rotation: [0, -wallAngle, 0]
    };
};

export { calculateAssetTransformationOnWall };