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

/**
 * Дебаг-просмотр спрайта: текстура, увеличенная целым множителем (nearest),
 * с сеткой по границам пикселей. Для правки пропорций и проверки кадров
 * анимации. Показ текущего кадра — просто вызывайте setTexture каждый тик.
 */
export class SpriteDebugView {
    readonly view: Container;

    private holder: Sprite;
    private grid: Graphics;
    private readonly zoom: number;
    private readonly gridColor: number;
    private readonly gridAlpha: number;

    constructor(opts: { zoom?: number; gridColor?: number; gridAlpha?: number } = {}) {
        this.zoom = Math.max(1, Math.round(opts.zoom ?? 8));
        this.gridColor = opts.gridColor ?? 0x000000;
        this.gridAlpha = opts.gridAlpha ?? 0.2;

        this.view = new Container();
        this.view.visible = false;

        this.holder = new Sprite(Texture.EMPTY);
        this.holder.anchor.set(0.5);
        this.grid = new Graphics();
        this.view.addChild(this.holder, this.grid);
    }

    /** Показать текстуру: центрирует, масштабирует целым множителем, рисует сетку. */
    setTexture(tex: Texture): void {
        this.holder.texture = tex;
        this.holder.scale.set(this.zoom);
        const w = tex.width * this.zoom;
        const h = tex.height * this.zoom;
        const g = this.grid;
        g.clear();
        for (let x = 0; x <= tex.width; x++) {
            g.moveTo(x * this.zoom - w / 2, -h / 2).lineTo(x * this.zoom - w / 2, h / 2);
        }
        for (let y = 0; y <= tex.height; y++) {
            g.moveTo(-w / 2, y * this.zoom - h / 2).lineTo(w / 2, y * this.zoom - h / 2);
        }
        g.stroke({ color: this.gridColor, width: 1, alpha: this.gridAlpha });
    }
}