import { RepeatWrapping, Texture } from "three-platformize";

export interface TextureAnimatorParams {
  texture: Texture;
  /**
   * 纹理集水平方向上的纹理数量
   */
  tilesHorizontal: number;
  /**
   * 纹理集垂直方向上的纹理数量
   */
  tilesVertical: number;
  /**
   * 总纹理数量
   */
  numberOfTiles: number;
  /**
   * 每个纹理在动画中显示的时间
   */
  tileDisplayDuration: number;
}

/**
 * 纹理动画
 */
export class TextureAnimator {
  texture: Texture;
  tilesHorizontal: number;
  tilesVertical: number;
  numberOfTiles: number;
  tileDisplayDuration: number;

  currentDisplayTime = 0;
  currentTile = 0;

  constructor(params: TextureAnimatorParams) {
    this.texture = params.texture;
    this.tilesHorizontal = params.tilesHorizontal;
    this.tilesVertical = params.tilesVertical;
    this.numberOfTiles = params.numberOfTiles;
    this.tileDisplayDuration = params.tileDisplayDuration;

    // 设置纹理在水平和垂直方向的包裹方式为重复
    this.texture.wrapS = this.texture.wrapT = RepeatWrapping;
    // 设置纹理的重复次数
    this.texture.repeat.set(1 / this.tilesHorizontal, 1 / this.tilesVertical);
  }

  update(time: number) {
    this.currentDisplayTime += time;

    while (this.currentDisplayTime > this.tileDisplayDuration) {
      this.currentDisplayTime -= this.tileDisplayDuration;
      this.currentTile++;

      if (this.currentTile === this.numberOfTiles) {
        this.currentTile = 0;
      }

      const t = this.currentTile % this.tilesHorizontal;
      this.texture.offset.x = t / this.tilesHorizontal;

      const n = Math.floor(this.currentTile / this.tilesHorizontal);
      this.texture.offset.y = n / this.tilesVertical;
    }
  }
}
