import { System, Entity } from "ecsy"
import { Adventure } from "../Components/adventure"
import { InCabin } from "../Components/inCabin"

// MovableSystem
export class AdventureReturnSystem extends System {
  priority = -100
  // This method will get called on every frame by default
  execute(delta: number) {
    //TODO: consider only executing this every few seconds?
    let now = Date.now()
    // Iterate through all the entities on the query
    this.queries.adventures.results.forEach((entity: Entity) => {
      let adventure = entity.getComponent(Adventure)
      if (adventure.active && adventure.arrivalTime.getTime() < now)
        this.arriveAdventure(entity, adventure)
    })
  }

  arriveAdventure(entity: Entity, adventure?: Adventure) {
    if (!adventure) adventure = entity.getComponent(Adventure)

    //TODO: resource management

    adventure.members.forEach((member: Entity) => {
      member.addComponent(InCabin)
    })

    entity.remove()
  }

  static queries = {
    adventures: {
      components: [Adventure],
    },
  }
  queries: any
}
