import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';

import * as Stats from 'stats.js';

const canvas = document.getElementById('threejs-preview')! as HTMLCanvasElement;

const renderer = new THREE.WebGLRenderer({ canvas });
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x161618);
scene.fog = new THREE.FogExp2(0x161618, 0.002);

const camera = new THREE.PerspectiveCamera(75);
camera.position.set(400, 200, 0);

// controls

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false;
// controls.maxPolarAngle = Math.PI / 2;

// dbg
const cylinder = new THREE.CylinderGeometry(0, 10, 30, 4, 1);
const material = new THREE.MeshPhongMaterial({ color: 0xffffff, flatShading: true });

const mesh = new THREE.Mesh(cylinder, material);
mesh.position.x = 0;
mesh.position.y = 0;
mesh.position.z = 0;
mesh.updateMatrix();
mesh.matrixAutoUpdate = false;
scene.add(mesh);

const ambientLight = new THREE.AmbientLight(0x222222);
scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);

// stats

const stats = new Stats();
canvas.parentElement!.appendChild(stats.dom);

const animate = (/* time: number */) => {
    requestAnimationFrame(animate);

    stats.begin();

    controls.update();

    // STRESS
    // resize canvas
    const parent = canvas.parentElement!;

    const width = parent.clientWidth;
    const height = parent.clientHeight;

    if (canvas.width !== width || canvas.height !== height) {
        renderer.setSize(width, height);
        camera.aspect = width / height;
        camera.updateProjectionMatrix();
    }

    renderer.render(scene, camera);

    stats.end();
};

requestAnimationFrame(animate);
