const { regClass, property } = Laya

@regClass()
export class UISequenceAnimation extends Laya.Script {
  declare owner: Laya.Image

  @property(String)
  public prefix: string

  @property(Number)
  public beginIndex: number = 0

  @property(Number)
  public endIndex: number

  @property(Boolean)
  public playOnAwake: boolean = true

  @property(Boolean)
  public loop: boolean = false

  private running: boolean = false
  private currentIndex: number = 0

  onAwake(): void {
    if (this.playOnAwake) {
      this.running = true
    } else {
      this.running = false
    }
    this.currentIndex = this.beginIndex
  }

  onLateUpdate(): void {
    if (this.running) {
      if (this.currentIndex > this.endIndex) {
        this.currentIndex = this.beginIndex
        if (this.loop === false) {
          this.running = false
          this.owner.visible = false
        }
      }
      let endStr = this.currentIndex.toString()
      if (this.currentIndex < 10) {
        endStr = `00${this.currentIndex}`
      } else if (this.currentIndex < 100) {
        endStr = `0${this.currentIndex}`
      }
      const path = `${this.prefix + endStr}.png`
      // ResourceManager.getInstance().loadTexture(path, this.image)
      const obj = Laya.Loader.getRes(path)
      if (obj) {
        this.owner.texture = obj
      } else {
        this.owner.skin = path
      }

      this.currentIndex++
    }
  }

  onSetRunning(running: boolean): void {
    this.running = running
  }
}
