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

export default class DirectionalLightShadowFixForMobileCamera extends RE.Component {
  initialOffset: THREE.Vector3 = new THREE.Vector3()
  currentOffset: THREE.Vector3 = new THREE.Vector3()
  getCamera(): THREE.Camera {
    return RE.App.currentScene.getObjectByProperty("uuid", RE.App.activeCamera) as THREE.Camera
  }

  getDirectionalLight(): THREE.DirectionalLight {
    return this.object3d as THREE.DirectionalLight
  }

  awake() {

  }

  start() {
    const directionalLight: THREE.DirectionalLight = this.getDirectionalLight()
    this.initialOffset.copy(directionalLight.position)
    this.initialOffset.sub(new THREE.Vector3(0, 0, 0))
    this.updatePositions()
    directionalLight.target = this.getCamera()
    if (directionalLight.shadow) {
      directionalLight.shadow.normalBias = 0.04;
    }
  }

  update() {
    this.updatePositions()
  }

  updatePositions() {    
    const directionalLight: THREE.DirectionalLight = this.getDirectionalLight()
    this.currentOffset.copy(this.initialOffset).add(this.getCamera().position)
    directionalLight.position.set(this.currentOffset.x, this.currentOffset.y, this.currentOffset.z)
    if(directionalLight.shadow) {
      directionalLight.shadow.camera.position.set(this.currentOffset.x, this.currentOffset.y, this.currentOffset.z)
    }
  }
}

RE.registerComponent(DirectionalLightShadowFixForMobileCamera);
        