import { System, Entity } from "ecsy"
import { Position } from "../../Components/position"
import { SpriteRenderer } from "../../Components/rendering/spriteRenderer"
import { Sprite, DisplayObject } from "pixi.js"
import { PixiRepresentation } from "../../Components/rendering/pixiRepresentation"
import { addOrSetComponent } from "../../util"
import globals from "../../globals"

// MovableSystem
export class SpriteSystem extends System {
  priority: 70

  // This method will get called on every frame by default
  execute(delta: number) {
    // Iterate through all the entities on the query
    this.queries.sprites.added.forEach((entity: Entity) => {
      if (!(entity as any).alive) return

      let renderer = entity.getComponent(SpriteRenderer)
      let pos = entity.getComponent(Position)
      let sprite = new Sprite(renderer.texture)
      sprite.position = pos.value.add(renderer.offset)
      globals.app.stage.addChild(sprite)
      addOrSetComponent(entity, PixiRepresentation, <PixiRepresentation>{
        value: <DisplayObject>sprite
      })
    })

    this.queries.sprites.changed.forEach((entity: Entity) => {
      if (!(entity as any).alive) return
      let renderer = entity.getComponent(SpriteRenderer)
      let pos = entity.getComponent(Position)
      let object = entity.getComponent(PixiRepresentation).value as Sprite
      object.texture = renderer.texture
      object.position = pos.value.add(renderer.offset)
    })
  }

  static queries = {
    sprites: {
      components: [SpriteRenderer, Position],
      listen: {
        added: true,
        changed: true
      }
    }
  }
  queries: any
}
