import * as THREE from 'three';
import * as Types from '../../../../types/world/worldTypes';
import * as CONSTANTS from '../../../../types/world/worldConstants';

const baseMaterial = new THREE.ShaderMaterial({
    side: THREE.DoubleSide,
    vertexShader: `
    varying vec2 vUv;
    void main(){
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
        vUv = uv;
    }
    `,
    fragmentShader: `
    varying vec2 vUv;
    uniform vec3 uColor;
    void main(){
        float alpha = 1.0 - vUv.y;
        gl_FragColor = vec4(uColor, alpha);
    }
    `,
    uniforms: {
        uColor: { value: new THREE.Color(CONSTANTS.zoneConfig.defaultColor) },
    },
    transparent: true,
});

export default function addZonesToScene(
    line: Types.Line,
    floorGroupZone: Types.RefGroup,
    color: THREE.Color
) {
    const point1 = line[0][0];
    const point2 = line[1][0];

    const length = (new THREE.Vector3(point2.x, point2.y, point2.z)).distanceTo(new THREE.Vector3(point1.x, point1.y, point1.z));
    const angle = Math.atan2(point2.z - point1.z, point2.x - point1.x);

    const geometry = new THREE.PlaneGeometry(length, 10);

    const material = baseMaterial.clone();
    material.uniforms.uColor.value.set(color.r, color.g, color.b);

    const mesh = new THREE.Mesh(geometry, material);

    mesh.position.set((point1.x + point2.x) / 2, ((line[0][2] - 1) * CONSTANTS.wallConfig.height) + 5, (point1.z + point2.z) / 2);
    mesh.rotation.y = -angle;

    floorGroupZone.current.add(mesh);
}
