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()

  private _normalBias = 0.04;

  get light() {
    return this.object3d as THREE.DirectionalLight
  }

  get camera() {
    return RE.App.currentScene.getObjectByProperty("uuid", RE.App.activeCamera) as THREE.Camera
  }

  get shadow() {
    return this.light.shadow;
  }

  @RE.props.num()
  get normalBias() {
    return this._normalBias;
  }

  set normalBias(value: number) {
    this._normalBias = value;
    if (this.shadow) { this.shadow.normalBias = value; }
  }

  awake() {

  }

  start() {
    this.initialOffset.copy(this.light.position)
    this.initialOffset.sub(new THREE.Vector3(0, 0, 0))
    this.updatePositions()
    this.light.target = this.camera
  }

  update() {
    this.updatePositions()
  }

  updatePositions() {    
    this.currentOffset.copy(this.initialOffset).add(this.camera.position)
    this.light.position.set(this.currentOffset.x, this.currentOffset.y, this.currentOffset.z)
    if(this.shadow) {
      this.shadow.camera.position.set(this.currentOffset.x, this.currentOffset.y, this.currentOffset.z)
    }
  }
}

RE.registerComponent(DirectionalLightShadowFixForMobileCamera);
        