import * as THREE from "three";
import TrackballControls from "three-trackballcontrols";
//import OrbitControls from "three-orbitcontrols";
//import DragControls from "three-dragcontrols";

const middlePointDistance = 3.1;
const fovDistance = 10;

function initiateSceneController (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);
    // const dragControls = new DragControls(objects, camera, renderer.domElement);

    function animate() {
        requestAnimationFrame(animate)

        controls.update()

        // resizeCanvasToDisplaySize(canvas, camera, renderer);

        render();

    }

    function render() {
        renderer.render(scene, camera);
    }

    animate() ;

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

function initiateSceneNonController (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);

    var animate = function () {
        requestAnimationFrame(animate)

        renderer.render(scene, camera)

    };

    animate() ;

    return {scene, camera, renderer};
}


function createCamera(scene, width, height) {
    const camera = new THREE.PerspectiveCamera(100, 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 spotlight1 = new THREE.SpotLight(0xffffff);
    var spotlight2 = new THREE.SpotLight(0xffffff); // 0x496898

    spotlight1.position.set(-100, 0, -100);
    spotlight2.position.set(100, 0, 100);
    scene.add(spotlight1);
    scene.add(spotlight2);

}

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);
    // const controls = new OrbitControls(camera, renderer.domElement);
    controls.target.set(10, 2, 2);
    controls.maxDistance = 500;
    controls.rotateSpeed = 1;
    controls.zoomSpeed = 1;

    return controls;
}


export {initiateSceneController, initiateSceneNonController};
