import * as THREE from "three";
import TrackballControls from "three-trackballcontrols";

function initiateScene (sceneCanvas ) {
    const scene = new THREE.Scene();

    const canvasWidth = sceneCanvas.parentNode.getBoundingClientRect().width;
    const canvasHeight = sceneCanvas.parentNode.getBoundingClientRect().height;

    const camera = createCamera(scene, canvasWidth, canvasHeight);
    const renderer = createRenderer(sceneCanvas, canvasWidth, canvasHeight);
    addSpotlight(scene);
    const controls = createController(camera, renderer, sceneCanvas, scene);

    return {scene, camera, renderer, controls};
}

function createCamera(scene, width, height) {
    const camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000);
    camera.position.x = 15;
    camera.position.y = 15;
    camera.position.z = 15;
    camera.lookAt(scene.position);

    return camera;
}

function addSpotlight(scene) {

    var ambientLight = new THREE.AmbientLight(0xD6D6D6);
    ambientLight.position.set(500, 500, 500);
    scene.add(ambientLight);

}

function createRenderer(canvas, width, height) {
    const renderer = new THREE.WebGLRenderer({
        canvas: canvas,
        alpha: true
    });

    renderer.setClearColor(0x94A0AE, 1.0);
    renderer.setSize(width, height);

    return renderer;
}

function createController(camera, renderer, canvas, scene) {
    const controls = new TrackballControls(camera, renderer.domElement);
    controls.target.set(0, 0, 0);
    controls.maxDistance = 500;
    controls.rotateSpeed = 4;
    controls.zoomSpeed = 0.4;

    var animate = function () {
        requestAnimationFrame(animate)

        controls.update()

        // resizeCanvasToDisplaySize(canvas, camera, renderer);

        renderer.render(scene, camera)

    };

    animate() ;

    return controls;
}

export {initiateScene};
