import { PixiRepresentation } from "../../Components/rendering/pixiRepresentation"
import { Entity, System } from "ecsy"
import { Position } from "../../Components/position"
import { OrderZ } from "../../Components/rendering/orderZ"
import globals from "../../globals"
import { canvasHeight } from "../../constants"

export class ZOrderSystem extends System {
  priority = 98

  minIndex = 0
  maxIndex = canvasHeight

  // This method will get called on every frame by default
  execute() {
    this.queries.objects.added.forEach((entity: Entity) => {
      let representation = entity.getComponent(PixiRepresentation).value
      let order = entity.getComponent(OrderZ)
      let pos = entity.getComponent(Position).value
      representation.zIndex = pos.y + order.offset
    })

    this.queries.objects.changed.forEach((entity: Entity) => {
      if (!(entity as any).alive) return
      let representation = entity.getComponent(PixiRepresentation).value
      let order = entity.getComponent(OrderZ)
      let pos = entity.getComponent(Position).value
      representation.zIndex = pos.y + order.offset
    })
    if (this.queries.objects.changed.length > 0)
      globals.app.stage.sortChildren()
  }

  static queries = {
    objects: {
      // add all draw components here as not thingy otherwise your representation will be killed
      components: [Position, OrderZ, PixiRepresentation],
      listen: {
        added: true,
        changed: [Position, OrderZ],
      },
    },
  }
  queries: any
}
