import Viewport from '../viewports/viewport';
import { Matrix4 } from '@math.gl/core';
import { pixelsToWorld, fovyToAltitude } from '@math.gl/web-mercator';
const DEGREES_TO_RADIANS = Math.PI / 180;

function getViewMatrix({
  height,
  focalDistance,
  orbitAxis,
  rotationX,
  rotationOrbit,
  zoom
}) {
  const up = orbitAxis === 'Z' ? [0, 0, 1] : [0, 1, 0];
  const eye = orbitAxis === 'Z' ? [0, -focalDistance, 0] : [0, 0, focalDistance];
  const viewMatrix = new Matrix4().lookAt({
    eye,
    up
  });
  viewMatrix.rotateX(rotationX * DEGREES_TO_RADIANS);

  if (orbitAxis === 'Z') {
    viewMatrix.rotateZ(rotationOrbit * DEGREES_TO_RADIANS);
  } else {
    viewMatrix.rotateY(rotationOrbit * DEGREES_TO_RADIANS);
  }

  const projectionScale = Math.pow(2, zoom) / height;
  viewMatrix.scale(projectionScale);
  return viewMatrix;
}

export default class OrbitViewport extends Viewport {
  constructor(props) {
    const {
      height,
      projectionMatrix,
      fovy = 50,
      orbitAxis = 'Z',
      target = [0, 0, 0],
      rotationX = 0,
      rotationOrbit = 0,
      zoom = 0
    } = props;
    const focalDistance = projectionMatrix ? projectionMatrix[5] / 2 : fovyToAltitude(fovy);
    super({ ...props,
      longitude: undefined,
      viewMatrix: getViewMatrix({
        height: height || 1,
        focalDistance,
        orbitAxis,
        rotationX,
        rotationOrbit,
        zoom
      }),
      fovy,
      focalDistance,
      position: target,
      zoom
    });
    this.projectedCenter = void 0;
    this.projectedCenter = this.project(this.center);
  }

  unproject(xyz, {
    topLeft = true
  } = {}) {
    const [x, y, z = this.projectedCenter[2]] = xyz;
    const y2 = topLeft ? y : this.height - y;
    const [X, Y, Z] = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix);
    return [X, Y, Z];
  }

  panByPosition(coords, pixel) {
    const p0 = this.project(coords);
    const nextCenter = [this.width / 2 + p0[0] - pixel[0], this.height / 2 + p0[1] - pixel[1], this.projectedCenter[2]];
    return {
      target: this.unproject(nextCenter)
    };
  }

}
//# sourceMappingURL=orbit-viewport.js.map