import { System, Entity, Not } from "ecsy"
import { DebugRect } from "../../Components/rendering/debugRect"
import { PixiRepresentation } from "../../Components/rendering/pixiRepresentation"
import { Graphics, DisplayObject } from "pixi.js"
import globals from "../../globals"

// MovableSystem
export class DebugRenderSystem 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.newRectangles.results.forEach((entity: Entity) => {
      let debugRect = entity.getComponent(DebugRect)
      let graphic = new Graphics()
      graphic.lineStyle(1, debugRect.color, 0.5)
      graphic.drawRect(
        debugRect.rect.source.x,
        debugRect.rect.source.y,
        debugRect.rect.size.x,
        debugRect.rect.size.y
      )
      globals.app.stage.addChild(graphic)
      entity.addComponent(PixiRepresentation, <PixiRepresentation>{
        value: <DisplayObject>graphic,
      })
    })

    this.queries.rectangles.changed.forEach((entity: Entity) => {
      let debugRect = entity.getComponent(DebugRect)
      let graphic = entity.getMutableComponent(PixiRepresentation)
        .value as Graphics
      graphic.clear
      graphic.lineStyle(1, debugRect.color, 0.5)
      graphic.drawRect(
        debugRect.rect.source.x,
        debugRect.rect.source.y,
        debugRect.rect.size.x,
        debugRect.rect.size.y
      )
    })
  }

  static queries = {
    newRectangles: {
      components: [DebugRect, Not(PixiRepresentation)],
    },
    rectangles: {
      components: [DebugRect, PixiRepresentation],
      listen: {
        changed: [DebugRect],
      },
    },
  }
  queries: any
}
