import { Texture, Sprite } from 'pixi.js';

/**
 * Покадровая анимация на спрайте: список кадров + fps, зацикливание.
 * Кадры можно менять на лету (повороты, состояния).
 */
export class FrameAnimation {
    private frames: Texture[];
    private fps: number;
    private loop: boolean;
    private t = 0;
    private index = 0;

    constructor(
        private sprite: Sprite,
        frames: Texture[],
        fps = 8,
        loop = true
    ) {
        this.frames = frames;
        this.fps = fps;
        this.loop = loop;
    }

    setFrames(frames: Texture[], reset = false): void {
        this.frames = frames;
        if (reset) {
            this.index = 0;
            this.t = 0;
        }
    }

    update(dt: number): void {
        if (this.frames.length === 0) return;
        this.t += dt * this.fps;
        while (this.t >= 1) {
            this.t -= 1;
            if (this.index + 1 < this.frames.length) {
                this.index++;
            } else if (this.loop) {
                this.index = 0;
            } else {
                this.t = 0;
                break;
            }
        }
        this.sprite.texture = this.frames[this.index] ?? this.sprite.texture;
    }
}