import * as THREE from 'three';

import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GUI } from 'lil-gui';

import { TaperedLink } from './taperedLink.js';

const FACE_OPACITY = 0.3;
const CAMERA_K = 5;

// scene, lights and camera




const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const light = new THREE.PointLight(0xffffff, 2);
light.position.set(10, 10, 10);
scene.add(light);
const light2 = new THREE.PointLight(0xffffff, 2);
light2.position.set(-10, 5, 10);
scene.add(light);
const amblight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(amblight);

camera.position.set(0, 0, CAMERA_K / 2);

camera.lookAt(0, 0, 0);
camera.position.z = 8;

const renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize( window.innerWidth, window.innerHeight );

renderer.localClippingEnabled = true;

const controls = new OrbitControls( camera, renderer.domElement );


controls.autoRotate = true;

document.body.appendChild( renderer.domElement );

const NODEC = 0x3293a9;
const LINKC = 0x00ff88;
const BACKGROUNDC = 0xd4d4d4;
	
scene.background = new THREE.Color(BACKGROUNDC);
const material = new THREE.MeshStandardMaterial({ color: LINKC });

material.transparent = true;
material.opacity = 0.7;

const node_mat = new THREE.MeshStandardMaterial({ color: NODEC });

node_mat.transparent = true;
node_mat.opacity = 0.5;

const params = {
    r1: 0.5,
    r2: 0.6,
    sync: false,
    l: 9,
    rotx: 1,
    roty: 0,
    rotz: 0,
};

const gui = new GUI();

gui.add(params, "r1", 0.01, 1.5);
gui.add(params, "r2", 0.01, 1.5);
gui.add(params, "sync");
gui.add(params, "l", 0, 10);
gui.add(params, "rotx", 0, 4);
gui.add(params, "roty", 0, 4);
gui.add(params, "rotz", 0, 4);

function makeNode(material, pos, r) {
    const geometry = new THREE.SphereGeometry(1);
    const sphere = new THREE.Mesh(geometry, material);
    const node = {
        v3: pos,
        object: sphere
    };
    updateNode(node, pos, r);
    return node;
}

function updateNode(node, pos, r) {
    node.v3 = pos; 
    node.object.scale.copy(new THREE.Vector3(r, r, r));
    node.object.position.copy(pos);
}
    

const n1 = makeNode(node_mat, new THREE.Vector3(-params["l"], -1, -1), params["r1"]);
const n2 = makeNode(node_mat, new THREE.Vector3(params["l"], 1, 1), params["r2"]);

const tl = new TaperedLink(material, n1, n2, params["r1"], params["r2"]);

scene.add(n1.object);
scene.add(n2.object);

scene.add(tl);

function animate() {
    requestAnimationFrame(animate);

    const r1 = params["r1"];
    const r2 = params["sync"] ? r1 : params["r2"]

    updateNode(n1, new THREE.Vector3(- params["l"], -1, -1), r1);
    updateNode(n2, new THREE.Vector3(params["l"], 1, 1), r2);
    tl.update(n1, n2, r1, r2, params["rotx"], params["roty"], params["rotz"]);
    controls.update();
    renderer.render(scene, camera);
}
animate();
