import * as THREE from 'three';
import { useMemo } from 'react';

function useWallGeometry(wallLength: number, wallHeight: number, wallThickness: number) {
    return useMemo(() => {
        const geometry = new THREE.BufferGeometry();

        const halfLength = wallLength / 2;
        const halfThickness = wallThickness / 2;
        const height = wallHeight;

        const vertices = [
            -halfLength, -height / 2, halfThickness,
            -halfLength, height / 2, halfThickness,
            halfLength, height / 2, halfThickness,
            halfLength, -height / 2, halfThickness,
            -halfLength, -height / 2, -halfThickness,
            -halfLength, height / 2, -halfThickness,
            halfLength, height / 2, -halfThickness,
            halfLength, -height / 2, -halfThickness,
            -halfLength, height / 2, halfThickness,
            -halfLength, height / 2, -halfThickness,
            halfLength, height / 2, -halfThickness,
            halfLength, height / 2, halfThickness,
            -halfLength, -height / 2, halfThickness,
            -halfLength, -height / 2, -halfThickness,
            halfLength, -height / 2, -halfThickness,
            halfLength, -height / 2, halfThickness,
        ];

        const indices = [
            0, 1, 2, 0, 2, 3,
            4, 6, 5, 4, 7, 6,
            0, 4, 5, 0, 5, 1,
            3, 2, 6, 3, 6, 7,
            8, 9, 10, 8, 10, 11,
            12, 14, 13, 12, 15, 14
        ];

        geometry.setIndex(indices);
        geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
        geometry.setAttribute('uv', new THREE.Float32BufferAttribute([
            0, 0, 0, 1, 1, 1, 1, 0,
            0, 0, 0, 1, 1, 1, 1, 0,
            0, 0, 0, 1, 1, 1, 1, 0,
            0, 0, 0, 1, 1, 1, 1, 0,
            0, 0, 0, 1, 1, 1, 1, 0,
            0, 0, 0, 1, 1, 1, 1, 0
        ], 2));

        geometry.computeVertexNormals();

        geometry.addGroup(0, 6, 0);   // Front
        geometry.addGroup(6, 6, 1);   // Back
        geometry.addGroup(12, 6, 2);  // Left
        geometry.addGroup(18, 6, 3);  // Right
        geometry.addGroup(24, 6, 4);  // Top
        geometry.addGroup(30, 6, 5);  // Bottom

        return geometry;
    }, [wallLength, wallHeight, wallThickness]);
}

export default useWallGeometry;