import * as THREE from 'three';
import { Group } from '../../../../../types/world/worldTypes';

function PointsCalculator(
    type: string,
    model: Group,
    rotation: THREE.Vector3 = new THREE.Vector3()
): { points?: THREE.Vector3[] } | null {
    if (!model) return null;

    const box = new THREE.Box3().setFromObject(model);

    const size = new THREE.Vector3();
    box.getSize(size);
    const center = new THREE.Vector3();
    box.getCenter(center);

    const rotationMatrix = new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(rotation.x, rotation.y, rotation.z));

    const localTopMiddle = new THREE.Vector3(0, size.y / 2, 0);
    const worldTopMiddle = localTopMiddle.clone().applyMatrix4(rotationMatrix).add(center);

    if (type === 'Conveyor') {
        const isWidthLonger = size.x > size.z;
        const longerSize = isWidthLonger ? size.x : size.z;
        const shorterSize = isWidthLonger ? size.z : size.x;
        const halfLongerSize = longerSize / 2;
        const halfShorterSize = shorterSize / 2;

        const localEndPoint1 = new THREE.Vector3(isWidthLonger ? -halfLongerSize + halfShorterSize : 0, size.y / 2, isWidthLonger ? 0 : -halfLongerSize + halfShorterSize);

        const localEndPoint2 = new THREE.Vector3(isWidthLonger ? halfLongerSize - halfShorterSize : 0, size.y / 2, isWidthLonger ? 0 : halfLongerSize - halfShorterSize);

        const worldEndPoint1 = localEndPoint1.applyMatrix4(rotationMatrix).add(center);
        const worldEndPoint2 = localEndPoint2.applyMatrix4(rotationMatrix).add(center);

        return {
            points: [worldEndPoint1, worldTopMiddle, worldEndPoint2]
        };
    }

    return {
        points: [worldTopMiddle]
    };
}

export default PointsCalculator;
