import * as THREE from "three";
import {OrbitControls} from "three/addons/controls/OrbitControls.js";
var scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// var camera = new THREE.PerspectiveCamera(1, 1, 1, 1000);
// camera.position.setScalar(150);
var renderer = new THREE.WebGLRenderer({
//  antialias: true
});
var canvas = renderer.domElement;
document.body.appendChild(canvas);

var controls = new OrbitControls(camera, canvas);

// White directional light at 0.65 intensity shining from the top.
scene.add(new THREE.HemisphereLight(0x606060, 0x404040));
let directionalLight1 = new THREE.DirectionalLight(0xffffff, 0.65);
scene.add(directionalLight1);

// Create points geometry
const zValues = Array.from({length: actuators.length}, () => (Math.random()-0.5)*0.1); //Array(97).fill(0.2);
zValues[15] = +0.2;
//zValues[16] = -0.5;

const points = [];
for (let i = 0; i < zValues.length; i++) {
    points.push([actuators[i][0], actuators[i][1], zValues[i]]); // Push x, y, z for each vertex
}

console.log(points)

var size = { x: 10, z: 10 };
//var pointsCount = 1000;
var points3d = [];
for (let i = 0; i < points.length; i++) {
    let x = points[i][0]   *1 -0.5   //THREE.MathUtils.randFloatSpread(size.x);
    let y = points[i][1]   *1 -0.5  // noise.perlin2(x / size.x * 5, z / size.z * 5) * 50;
    let z = points[i][2]   *1 -0.0 //THREE.MathUtils.randFloatSpread(size.z);
    points3d.push(new THREE.Vector3(x, y, z));
}

var geom = new THREE.BufferGeometry().setFromPoints(points3d);
var cloud = new THREE.Points(
  geom,
  new THREE.PointsMaterial({ color: 0x99ccff, size: 0.01 })
);
scene.add(cloud);

// triangulate x, z
var indexDelaunay = Delaunator.from(
  points3d.map(v => {
    return [v.x, v.y];
  })
);


var meshIndex = []; // delaunay index => three.js index
for (let i = 0; i < indexDelaunay.triangles.length; i++){
    meshIndex.push(indexDelaunay.triangles[i]);
}

console.log(indexDelaunay.triangles)

geom.setIndex(meshIndex); // add three.js index to the existing geometry
geom.computeVertexNormals();
var mesh = new THREE.Mesh(
  geom, // re-use the existing geometry
  new THREE.MeshLambertMaterial({ color: "purple", wireframe: true })
);
scene.add(mesh);

var gui = new dat.GUI();
gui.add(mesh.material, "wireframe");

render();

function resize(renderer) {
  const canvas = renderer.domElement;
  const width = 1000 //canvas.clientWidth;
  const height = 800// canvas.clientHeight;
  const needResize = canvas.width !== width || canvas.height !== height;
  if (needResize) {
    renderer.setSize(width, height, false);
  }
  return needResize;
}

// Position the camera
camera.position.set(0, 0, 1.5);
camera.lookAt(0, 0, 0);

function render() {
  if (resize(renderer)) {
    camera.aspect = canvas.clientWidth / canvas.clientHeight;
    camera.updateProjectionMatrix();
  }
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}
