import * as RE from 'rogue-engine'
import * as THREE from 'three'

export default class TargetedOrbitCamera extends RE.Component {
	@RE.props.object3d() target
	@RE.props.checkbox() enableRotate = true
	@RE.props.num() rotateSpeed = 1.0

	// How far you can orbit horizontally, upper and lower limits.
	// If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
	@RE.props.num() minAzimuthAngle = - 6.28 // 2 PI radians
	@RE.props.num() maxAzimuthAngle = 6.28 // -2 PI radians

	// How far you can orbit vertically, upper and lower limits.
	// Range is 0 to Math.PI radians.
	@RE.props.num() minPolarAngle = 0 // radians
	@RE.props.num() maxPolarAngle = 1.56 // 0.5 PI radians
	@RE.props.checkbox() enableDolly = true
	@RE.props.num() dollySpeed = 1.0
	@RE.props.num() minDistance = 1
	@RE.props.num() maxDistance = 50
	@RE.props.vector3() offset = new THREE.Vector3()
	@RE.props.num() rotateMouseButton = 2

	@RE.props.checkbox() useCameraLock = false

	rotateStart = new THREE.Vector2()
	rotateEnd = new THREE.Vector2()
	rotateDelta = new THREE.Vector2()

	scale = 1
	EPS = 0.000001
	twoPI = 2 * Math.PI

	spherical = new THREE.Spherical()
	sphericalDelta = new THREE.Spherical()

	quat = new THREE.Quaternion().setFromUnitVectors( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ) )
	quatInverse = this.quat.clone().invert()

	lastPosition = new THREE.Vector3()
	lastQuaternion = new THREE.Quaternion()

	initialOffset = new THREE.Vector3()

	

  awake() {
	if(this.useCameraLock) {
		const container = document.getElementById(RE.Runtime.containerId)
		// container?.addEventListener("mousedown", this.lock.bind(this), false)
		if(container) {
			container.onmousedown = this.lock.bind(this)
			RE.Runtime.onStop(this.dispose)
		}
	}
  }

  start() {

	if(!this.target) {
		RE.Debug.logError("Orbit controls not set to an Object3D Target.")
		return
	}

	RE.Runtime.rogueDOMContainer.addEventListener('contextmenu', event => { event.preventDefault() })
	
	// so camera.up is the orbit axis
	this.quat = new THREE.Quaternion().setFromUnitVectors( this.object3d.up, new THREE.Vector3( 0, 1, 0 ) )
	this.quatInverse = this.quat.clone().invert()

	this.initialOffset.copy(this.object3d.position).sub(this.target.position)
	this.offset.copy(this.initialOffset)
  }

  update() {	
	if(!this.target) {
		return
	}
	
	if(this.useCameraLock && !!document.pointerLockElement) {	
		if(this.enableRotate && RE.Input.mouse.isMoving) {	
			let normalizedScreenMovement = new THREE.Vector2(0,0)
			this.normalizeScreenMovement({x: RE.Input.mouse.movementX, y: RE.Input.mouse.movementY}, normalizedScreenMovement)
			this.rotateLeft(this.twoPI * normalizedScreenMovement.x)
	
			this.rotateUp(this.twoPI * -normalizedScreenMovement.y)
		}
	} else {
		let normalizedScreenPosition = new THREE.Vector2(0,0)
		this.normalizeScreenInput(RE.Input.mouse, normalizedScreenPosition)
		if(this.enableRotate && RE.Input.mouse.getButtonDown(this.rotateMouseButton)) {
			this.rotateStart.set( normalizedScreenPosition.x, normalizedScreenPosition.y )
		}
	
		if(this.enableRotate && RE.Input.mouse.getButtonPressed(this.rotateMouseButton)) {
			this.rotateEnd.set( normalizedScreenPosition.x, normalizedScreenPosition.y )
	
			this.rotateDelta.subVectors( this.rotateEnd, this.rotateStart ).multiplyScalar( this.rotateSpeed )
	
			this.rotateLeft(this.twoPI * this.rotateDelta.x)
	
			this.rotateUp(this.twoPI * -this.rotateDelta.y)
	
			this.rotateStart.copy( this.rotateEnd )
		}
	}

	if(this.enableDolly && RE.Input.mouse.wheelY > 0) {
		this.dollyOut()
	}

	if(this.enableDolly && RE.Input.mouse.wheelY < 0) {
		this.dollyIn()
	}

	this.updateCamera()

	if(this.useCameraLock && RE.Input.keyboard.getKeyPressed("Escape")) {
		this.unlock()
	}
}

	dispose() {
		const container = document.getElementById(RE.Runtime.containerId)
		if(container) {
			// container?.removeEventListener("mousedown", this.lock)
			container.onmousedown = null
		}
	}

	rotateLeft(angle) {
		this.sphericalDelta.theta -= angle
	}

	rotateUp(angle) {
		this.sphericalDelta.phi -= angle
	}

	updateCamera() {
		// rotate offset to "y-axis-is-up" space
		this.offset.applyQuaternion(this.quat)

		// angle from z-axis around y-axis
		this.spherical.setFromVector3(this.offset)
		this.spherical.theta += this.sphericalDelta.theta
		this.spherical.phi += this.sphericalDelta.phi

		// restrict theta to be between desired limits
		let min = this.minAzimuthAngle
		let max = this.maxAzimuthAngle

		if ( isFinite(min) && isFinite(max) ) {

			if (min < -Math.PI) {
				min += this.twoPI
			} else if (min > Math.PI) {
				min -= this.twoPI
			}

			if (max < - Math.PI) {
				max += this.twoPI
			} else if (max > Math.PI) {
				max -= this.twoPI
			}

			if (min <= max) {
				this.spherical.theta = Math.max(min, Math.min(max, this.spherical.theta))
			} else {
				this.spherical.theta = (this.spherical.theta > (min + max) / 2 ) ?
					Math.max( min, this.spherical.theta ) :
					Math.min( max, this.spherical.theta )
			}
		}

		// restrict phi to be between desired limits
		this.spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this.spherical.phi))

		this.spherical.makeSafe()


		this.spherical.radius *= this.scale

		// restrict radius to be between desired limits
		this.spherical.radius = Math.max(this.minDistance, Math.min(this.maxDistance, this.spherical.radius))

		this.offset.setFromSpherical(this.spherical)

		// rotate offset back to "camera-up-vector-is-up" space
		this.offset.applyQuaternion(this.quatInverse)

		this.object3d.position.copy(this.target.position).add(this.offset)

		this.object3d.lookAt(this.target.position)

		this.sphericalDelta.set(0, 0, 0)

		this.scale = 1

		// update condition is:
		// min(camera displacement, camera rotation in radians)^2 > EPS
		// using small-angle approximation cos(x/2) = 1 - x^2 / 8
		if (this.lastPosition.distanceToSquared(this.object3d.position) > this.EPS ||
			8 * (1 - this.lastQuaternion.dot(this.object3d.quaternion)) > this.EPS) {

			this.lastPosition.copy(this.object3d.position)
			this.lastQuaternion.copy(this.object3d.quaternion)
		}
	}

	dollyOut() {
		this.scale /= Math.pow(0.95, this.dollySpeed)
	}

	dollyIn() {
		this.scale *= Math.pow(0.95, this.dollySpeed)
	}

  normalizeScreenInput(browserVector, gameVector) {
	const bounds = RE.Runtime.rogueDOMContainer.getBoundingClientRect()
	gameVector.x = ((browserVector.x - bounds.left) / bounds.width) * 2 - 1
	gameVector.y = -((browserVector.y - bounds.top) / bounds.height) * 2 + 1
  }

  normalizeScreenMovement(browserVector, gameVector) {
	const bounds = RE.Runtime.rogueDOMContainer.getBoundingClientRect()
	gameVector.x = (browserVector.x / bounds.width)
	gameVector.y = -(browserVector.y / bounds.height)
  }

  lock() {
	if(!this.useCameraLock) {
		return
	}
	RE.Input.mouse.lock()
  }

  unlock() {
	if(!this.useCameraLock) {
		return
	}
	RE.Input.mouse.unlock()
  }
}

RE.registerComponent(TargetedOrbitCamera)