import { Area3D } from 'godot'
import Interactable from './interactable'

class InteractableDistance {
  interactable: Interactable
  distance: number

  constructor(interactable: Interactable, distance: number) {
    this.interactable = interactable
    this.distance = distance
  }
}

export default class Interactor extends Area3D {
  _interactables: Array<Interactable> = []

  _on_area_entered(area: Area3D) {
    if (area instanceof Interactable) {
      this._interactables.push(area)
    }
  }

  _on_area_exited(area: Area3D) {
    const index = this._interactables.indexOf(area as Interactable)

    if (index) {
      this._interactables.splice(index, 1)
    }
  }

  try_interact_nearest() {
    // @ts-ignore
    this._interactables.reduce(this.find_nearest.bind(this))
  }

  find_nearest(nearest: InteractableDistance, target: Interactable): InteractableDistance {
    const distance = this.global_position.distance_to(target.global_position)
    if (distance < nearest.distance) {
      return new InteractableDistance(target, distance)
    } else {
      return nearest
    }
  }
}
