import assets from '../../../Assets/Sprites/**/*.yaml'
import { Shape, Sprite, SpritePart } from '../data/sprite'
import * as PIXI from 'pixi.js'

export const sprites: Record<string, Sprite> = {}

for (let [key, value] of Object.entries(assets)) {
  sprites[key] = new Sprite(value)
}

export class SpriteInstance {
  container: PIXI.Container
  sprite: Sprite|null = null
  spriteKey: string = ''
  animation?: SpritePart
  animationKey: string = ''
  set?: SpritePart
  setKey: string = ''
  subset?: SpritePart
  subsetKey: string = ''
  frame?: SpritePart
  frameIndex: number = 0
  frameCount: number = 0
  animate: boolean = true
  elapsed: number = 0

  constructor(ctor: string) {
    this.container = new PIXI.Container()
    this.setCtor(ctor)
  }

  setCtor(ctor: string) {
    this.container.removeChildren()
    let [spriteKey, animationKey, setKey, subsetKey, frameKey] = ctor.split('.')
    this.spriteKey = spriteKey
    this.animationKey = animationKey
    this.setKey = setKey
    this.subsetKey = subsetKey
    this.frameIndex = Number(frameKey)
    this.frameCount = 0
    this.sprite = sprites[spriteKey]
    if (!this.sprite) {
      this.container.addChild(new PIXI.Text('missing sprite'))
      return
    }
    this.animation = this.sprite.root.children[animationKey]
    this.set = this.animation.children[setKey]
    this.subset = this.set.children[subsetKey]
    //
    if (this.subset.frames) {
      this.frameCount = this.subset.frames.length
      this.frame = this.subset.frames[this.frameIndex]
      let s = new PIXI.Sprite(this.frame.texture)
      s.x -= this.frame.originX
      s.y -= this.frame.originY
      this.container.addChild(s)
      this.container.pivot.x -= this.frame.originX
      this.container.pivot.y -= this.frame.originY
    }
  }

  update(delta: number) {
    if (!this.animate) return
    this.elapsed += delta
    while (this.frameCount > 0 && this.frame && this.elapsed >= this.frame.time && this.frame.time > 0) {
      this.elapsed -= this.frame.time
      this.frameIndex++
      if (this.frameIndex >= this.frameCount) {
        this.frameIndex = 0
      }
      this.setCtor(`${this.spriteKey}.${this.animationKey}.${this.setKey}.${this.subsetKey}.${this.frameIndex}`)
    }
  }

  getBodyShape(): Shape|undefined {
    if (this.frame && this.frame.shapes) {
      return this.frame.shapes.find(v=>v.key==='body')
    }
    return
  }
}