import { CSS_ABSOLUTE_POSITIONING } from "../../../../../view/CSS_ABSOLUTE_POSITIONING.js";
import { CanvasView } from "../../../../../view/elements/CanvasView.js";
import EmptyView from "../../../../../view/elements/EmptyView.js";
import { sampler2d_write_to_canvas_raw } from "../../sampler/sampler2d_write_to_canvas_raw.js";

export class ResidencyDebugView extends EmptyView {
    /**
     *
     * @type {VirtualTexturePage|null}
     */
    texture = null;

    #canvas = new CanvasView();

    #previous_residency = new Uint32Array(1024);

    #scale =1;

    constructor({
                    scale = 1
                } = {}) {

        super({
            css: {
                position: "absolute",
                boxShadow: "0 0 8px black",
                background: "black"
            },
        });

        this.#scale = scale;
        this.#canvas.css(CSS_ABSOLUTE_POSITIONING);

        this.addChild(this.#canvas);

        this.#previous_residency.fill(-1);
    }

    update() {

        const t = this.texture;
        if (t === null) {
            return;
        }

        const canvas = this.#canvas;
        const scale = this.#scale;

        canvas.size.set(
            t.page_texture_resolution[0] * scale,
            t.page_texture_resolution[1] * scale,
        );

        this.size.copy(canvas.size);

        const residentTiles = t.resident_tiles;

        const temp = new CanvasView();
        const tile_resolution = t.tile_resolution;
        temp.size.setScalar(tile_resolution);

        const tile_columns = t.page_texture_resolution[0] / tile_resolution;

        for (let i = 0; i < residentTiles.length; i++) {
            const tile = residentTiles[i];

            const page_slot = tile.page_slot;
            if (this.#previous_residency[page_slot] === tile.finger_print) {
                continue;
            }

            sampler2d_write_to_canvas_raw(tile.data, temp.el);
            const column = page_slot % tile_columns;
            const row = (page_slot / tile_columns) | 0;

            canvas.context2d.drawImage(
                temp.el, 0, 0, tile_resolution, tile_resolution,
                tile_resolution * column * scale, tile_resolution * row * scale,
                tile_resolution * scale, tile_resolution * scale
            );

            this.#previous_residency[page_slot] = tile.finger_print;
        }
    }
}