import { Camera, WebGLRenderer, Vector3, Matrix4, Mesh, BoxBufferGeometry } from "three";
import { MercatorCoordinate } from "mapbox-gl";
var modelOrigin = [148.9819, -35.39847];
var modelAltitude = 0;
var modelRotate = [Math.PI / 2, 0, 0];
var modelAsMercatorCoordinate = MercatorCoordinate.fromLngLat(modelOrigin, modelAltitude);
var modelTransform = {
  translateX: modelAsMercatorCoordinate.x,
  translateY: modelAsMercatorCoordinate.y,
  translateZ: modelAsMercatorCoordinate.z,
  rotateX: modelRotate[0],
  rotateY: modelRotate[1],
  rotateZ: modelRotate[2],
  scale: modelAsMercatorCoordinate.meterInMercatorCoordinateUnits()
};
console.log(modelTransform);
const camera = new Camera();
let renderer;
let mainMap;
export function Threejs3LayerBuilder(scene) {
  const Threejs3Layer = {
    id: "3d-model",
    type: "custom",
    renderingMode: "3d",
    onAdd: function(map, gl) {
      setTimeout(() => {
        scene.add(new Mesh(new BoxBufferGeometry()));
      }, 1e3);
      mainMap = map;
      renderer = new WebGLRenderer({
        canvas: map.getCanvas(),
        context: gl
      });
      renderer.autoClear = false;
    },
    render: function(gl, matrix) {
      if (!renderer) {
        return;
      }
      if (!mainMap) {
        return;
      }
      console.log("render");
      var rotationX = new Matrix4().makeRotationAxis(new Vector3(1, 0, 0), modelTransform.rotateX);
      var rotationY = new Matrix4().makeRotationAxis(new Vector3(0, 1, 0), modelTransform.rotateY);
      var rotationZ = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), modelTransform.rotateZ);
      var m = new Matrix4().fromArray(matrix);
      var l = new Matrix4().makeTranslation(modelTransform.translateX, modelTransform.translateY, modelTransform.translateZ).scale(new Vector3(modelTransform.scale, -modelTransform.scale, modelTransform.scale)).multiply(rotationX).multiply(rotationY).multiply(rotationZ);
      camera.projectionMatrix = m.multiply(l);
      renderer.state.reset();
      renderer.render(scene, camera);
    }
  };
  return Threejs3Layer;
}
