import { System, Entity, Not } from "ecsy"
import { Position } from "../Components/position"
import { Door } from "../Components/door"
import { SpriteRenderer } from "../Components/rendering/spriteRenderer"
import { IPoint, Texture } from "pixi.js"

// MovableSystem
export class DoorSystem extends System {
  // This method will get called on every frame by default
  execute(delta: number) {
    // Iterate through all the entities on the query
    this.queries.newDoors.results.forEach((entity: Entity) => {
      let door = entity.getComponent(Door)

      let doorOffset: IPoint = door.open ? door.openOffset : door.closedOffset
      let doorTex: Texture = door.open ? door.openTex : door.closedTex
      entity.addComponent(SpriteRenderer, <SpriteRenderer>{
        texture: doorTex,
        offset: doorOffset
      })
    })

    this.queries.changedDoors.changed.forEach((entity: Entity) => {
      let door = entity.getComponent(Door)
      let renderer = entity.getMutableComponent(SpriteRenderer)

      renderer.offset = door.open ? door.openOffset : door.closedOffset
      renderer.texture = door.open ? door.openTex : door.closedTex
    })
  }

  static queries = {
    newDoors: {
      components: [Door, Not(SpriteRenderer)]
    },
    changedDoors: {
      components: [Door, Position, SpriteRenderer],
      listen: {
        changed: [Door]
      }
    }
  }
  queries: any
}
