import { System, Entity, Not } from "ecsy"
import { Human } from "../Components/human"
import { Appearance } from "../Components/appearance"
import { InCabin } from "../Components/inCabin"
import { Position } from "../Components/position"
import { SpriteRenderer } from "../Components/rendering/spriteRenderer"
import { Vector } from "../Datatypes/MathTypes/vector"
import { HoverObject } from "../Components/hoverObject"
import { Name } from "../Components/name"

// MovableSystem
export class VisibleHumanSystem extends System {
  priority = 50

  execute(delta: number) {
    // add sprite at start
    this.queries.newHumans.results.forEach((entity: Entity) => {
      let texture = entity.getComponent(Appearance).idleTexture
      entity.addComponent(SpriteRenderer, <SpriteRenderer>{
        texture: texture,
        offset: new Vector(-texture.width / 2, -texture.height),
      })
      let name = entity.getComponent(Name)
      entity.addComponent(HoverObject, { label: name.fullName() })
    })
    //update sprite texture
    this.queries.visibleHumans.changed.forEach((entity: Entity) => {
      let texture = entity.getComponent(Appearance).idleTexture
      entity.getMutableComponent(SpriteRenderer).texture = texture
    })
  }

  static queries = {
    newHumans: {
      components: [Human, Appearance, InCabin, Position, Not(SpriteRenderer)],
    },
    visibleHumans: {
      components: [Human, Appearance, InCabin, Position, SpriteRenderer],
      listen: {
        changed: [Appearance],
      },
    },
  }
  queries: any
}
