	import * as THREE from '../../build/three.module.js';
	import {
		GLTFLoader
	} from '../jsm/loaders/GLTFLoader.js';
	import {
		OrbitControls
	} from '../jsm/controls/OrbitControls.js';

	let canvas, renderer;

	const scenes = [];
	//const category = ['1', '2', '3'];


	window.initThreeJS = init;

	function init() {

		canvas = document.getElementById("c");

		const content = document.getElementById('content');

		for (let i = 0; i < id.length; i++) {

			const scene = new THREE.Scene();
			//scene.background = new THREE.Color(0x000000);

			// make a list item
			const isotope = document.createElement('div');
			isotope.className = 'isotope-item ' + revitVersion[i] + ' ' + categoryTable[i] + ' col-sm-6 col-md-4 col-lg-3';
			content.appendChild(isotope);

			const thumbnail = document.createElement('div');
			thumbnail.className = 'thumbnail';
			isotope.appendChild(thumbnail);

			const element = document.createElement('div');
			//element.className = 'thumb-preview list-item';
			element.className = 'thumb-preview';
			//element.className = 'list-item';
			thumbnail.appendChild(element);

			const a = document.createElement('a');
			a.className = "thumb-image";
			a.href = "/Common/assets/images/projects/project-8.png";
			element.appendChild(a);
			/*
								const thumbImage = document.createElement('a');
								thumbImage.className = 'thumb-image';
								preview.appendChild(thumbImage);

								const element = document.createElement( 'div' );
								element.className = 'list-item';
			*/
			const sceneElement = document.createElement('div');
			element.appendChild(sceneElement);

			const aImg = document.createElement('a');
			aImg.setAttribute("href", "component-detail.php?object=" + object[i] + "&parent=" + parent[i]);
			sceneElement.appendChild(aImg);

			const img = document.createElement('img');
			img.src = "/Common/assets/images/projects/project-8.png";
			img.className = 'img-responsive';
			img.alt = 'Project';
			aImg.appendChild(img);



			// the element that represents the area we want to render the scene
			scene.userData.element = sceneElement;
			thumbnail.appendChild(element);

			const h5 = document.createElement('a');
			h5.innerText = object[i];
			h5.setAttribute("href", "component-detail.php?object=" + object[i] + "&parent=" + parent[i]);
			h5.style = "padding-bottom: 0px;"
			thumbnail.appendChild(h5);

			const smallRvt = document.createElement('small');
			smallRvt.innerText = ".rfa";
			h5.appendChild(smallRvt);

			h5.innerText = ellipsis(h5.innerText);

			const mgdescription = document.createElement('div');
			mgdescription.className = 'mg-description';
			thumbnail.appendChild(mgdescription);

			const checkbox = document.createElement('input');
			checkbox.type = "checkbox";
			checkbox.value = id[i];
			checkbox.name = "delCheck";
			mgdescription.appendChild(checkbox);

			const pullRight = document.createElement('small');
			pullRight.className = 'pull-right text-muted';
			pullRight.innerText = 'Revit ' + revitVersion[i];
			mgdescription.appendChild(pullRight);

			const camera = new THREE.PerspectiveCamera(50, 1, 1, 1000);
			camera.position.set(0, 2.5, 8);
			scene.userData.camera = camera;
			//scene = new THREE.Scene();
			scene.background = new THREE.Color(0x15608c);

			const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444);
			hemiLight.position.set(0, 20, 0);
			scene.add(hemiLight);

			const spotLight = new THREE.SpotLight(0xffffff);
			spotLight.position.set(15, 40, 35);
			spotLight.castShadow = true;
			spotLight.intensity = 0.5;
			scene.add(spotLight);
			const spotLight2 = new THREE.SpotLight(0xffffff);
			spotLight2.position.set(15, 40, -35);
			spotLight2.castShadow = true;
			spotLight2.intensity = 0.5;
			scene.add(spotLight2);

			const dirLight = new THREE.DirectionalLight(0xffffff);
			dirLight.position.set(5, 5, 0);
			dirLight.castShadow = true;
			dirLight.shadow.camera.top = 1;
			dirLight.shadow.camera.bottom = -1;
			dirLight.shadow.camera.left = -1;
			dirLight.shadow.camera.right = 1;
			dirLight.shadow.camera.near = 0.1;
			dirLight.shadow.camera.far = 20;
			scene.add(dirLight);

			const mesh = new THREE.Mesh(new THREE.PlaneGeometry(50, 50), new THREE.MeshPhongMaterial({
				color: 0x999999,
				depthWrite: false
			}));
			mesh.rotation.x = -Math.PI / 2;
			mesh.receiveShadow = true;
			scene.add(mesh);

			const grid = new THREE.GridHelper(50, 50, 0x888888, 0x888888);
			scene.add(grid);

			const controls = new OrbitControls(scene.userData.camera, scene.userData.element);
			controls.target.set(0, 2, 0);
			controls.minDistance = 0.5;
			controls.maxDistance = 10;
			controls.maxPolarAngle = 0.5 * Math.PI;
			controls.autoRotate = true;
			controls.enableZoom = false;
			controls.enableRotate = false;
			controls.enablePan = false;
			scene.userData.controls = controls;



			var loader = new GLTFLoader();
			loader.setPath("./assets/glb/Revit元件/" + parent[i] + "/");
			
			var name = object[i] + ".glb";

			loader.load(name, function (gltf) {
				var mroot = gltf.scene;
				var bbox = new THREE.Box3().setFromObject(mroot);
				var cent = bbox.getCenter(new THREE.Vector3());
				var size = bbox.getSize(new THREE.Vector3());

				//Rescale the object to normalized space
				var maxAxis = Math.max(size.x, size.y, size.z);
				mroot.scale.multiplyScalar(5.0 / maxAxis);
				bbox.setFromObject(mroot);
				bbox.getCenter(cent);
				bbox.getSize(size);
				//Reposition to 0,halfY,0
				mroot.position.copy(cent).multiplyScalar(-1);
				mroot.position.y += (size.y * 0.5);
				mroot.traverse(function (object) {
					if (object.isMesh) {
						object.castShadow = true;
						if (object.material.name == '玻璃') {
							object.material.transparent = true;
							object.material.opacity = 0;
						}
					}
				});
				scene.add(mroot);

			});



			scenes.push(scene);

		}

		renderer = new THREE.WebGLRenderer({
			canvas: canvas,
			antialias: true
		});
		renderer.setClearColor(0xffffff, 1);
		renderer.setPixelRatio(window.devicePixelRatio);
		renderer.outputEncoding = THREE.sRGBEncoding;
		renderer.shadowMap.enabled = true;

		animate();
	}

	function ellipsis(str) {
		return (str.length > 32) ? str.substr(0, 31) + '...' : str;
	}

	function updateSize() {

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

		if (canvas.width !== width || canvas.height !== height) {

			renderer.setSize(width, height, false);

		}

	}

	function animate() {

		render();
		requestAnimationFrame(animate);

	}

	function render() {

		updateSize();

		canvas.style.transform = `translateY(${window.scrollY}px)`;

		renderer.setClearColor(0xffffff);
		renderer.setScissorTest(false);
		renderer.clear();

		renderer.setClearColor(0xe0e0e0);
		renderer.setScissorTest(true);

		scenes.forEach(function (scene) {

			// get the element that is a place holder for where we want to
			// draw the scene
			const element = scene.userData.element;

			// get its position relative to the page's viewport
			const rect = element.getBoundingClientRect();

			// check if it's offscreen. If so skip it
			if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
				rect.right < 0 || rect.left > renderer.domElement.clientWidth) {

				return; // it's off screen

			}

			// set the viewport
			const width = rect.right - rect.left;
			const height = rect.bottom - rect.top;
			const left = rect.left;
			const bottom = renderer.domElement.clientHeight - rect.bottom;

			renderer.setViewport(left, bottom, width, height);
			renderer.setScissor(left, bottom, width, height);

			const camera = scene.userData.camera;

			//camera.aspect = width / height; // not changing in this example
			//camera.updateProjectionMatrix();

			scene.userData.controls.update();

			renderer.render(scene, camera);

		});
	}

	$('input[name="delCheck"]').change(function () {
		delFavoriteList = [];
		$('input[name="delCheck"]:checked').each(function () {
			delFavoriteList.push($(this).val());
		});
	});