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

export default class FloorCheckComponent extends RE.Component {
  raycaster: THREE.Raycaster
  down = new THREE.Vector3(0, -1, 0)
  @RE.props.num() near: number = 0
  @RE.props.num() far: number = Infinity
  isOnFloor: boolean = false
  @RE.props.num() touchingFloorDistance: number = 1
  childrenToFilter
  awake() {
    this.raycaster = new THREE.Raycaster(this.object3d.position, this.down, this.near, this.far)
     this.childrenToFilter = this.getAllChildrenUuids(this.object3d)
  }

  getAllChildrenUuids(child) {
    return child.children.flatMap(innerChild => {if(innerChild.children.length > 0) {return this.getAllChildrenUuids(innerChild)} return innerChild.uuid})
  }
  start() {

  }

  update() {
    this.raycaster.set(this.object3d.position, this.down)

    this.isOnFloor = false
    let intersects = this.raycaster.intersectObjects(RE.App.currentScene.children)
    const notMeIntersects = intersects.filter((intersect) => {
      return !this.childrenToFilter.includes(intersect.object.uuid)
    })
    notMeIntersects.forEach(intersect => {
      this.isOnFloor = this.isOnFloor || intersect.distance <= this.touchingFloorDistance
    })
  }
}

RE.registerComponent(FloorCheckComponent);
