import { assert } from "../../../../core/assert.js";
import sampler2D2Canvas from "../../../../engine/graphics/texture/sampler/sampler2d_to_html_canvas.js";
import LabelView from "../../../../view/common/LabelView.js";
import { CanvasView } from "../../../../view/elements/CanvasView.js";
import EmptyView from "../../../../view/elements/EmptyView.js";
import { sampler_from_filter } from "./sampler_from_filter.js";

/**
 *
 * @param {GridData} grid
 * @param {{name:string, filter:CellFilter}[]} projections
 * @param {number} [resolution_scale]
 * @param {number} [grid_width]
 * @returns {View}
 */
export function visualise_filters_as_grid({
                                              grid,
                                              projections,
                                              resolution_scale = 4,
                                              grid_width = 4
                                          }) {

    assert.defined(grid, 'grid');
    assert.defined(projections, 'projections');
    assert.isArray(projections, 'projections');

    const tile_size = [
        grid.width * resolution_scale,
        grid.height * resolution_scale
    ];

    const vContainer = new EmptyView();

    for (let i = 0; i < projections.length; i++) {

        const x = i % grid_width;
        const y = Math.floor(i / grid_width);

        const { filter, name = "unnamed" } = projections[i];

        const tile = new EmptyView();

        const vCanvas = new CanvasView();

        const sampler = sampler_from_filter(grid, filter, resolution_scale);

        vCanvas.size.set(sampler.width, sampler.height);
        vCanvas.transformOrigin.set(0, 0);

        sampler2D2Canvas(sampler, 255, 0, vCanvas.el)

        tile.css({
            position: "absolute",
            left: "0",
            top: "0"
        });

        tile.position.set((tile_size[0] + 1) * x, (tile_size[1] + 1) * y);

        const label = new LabelView(name, {
            css: {
                top: "0",
                left: "0",
                position: "absolute",
                padding: "4px",
                color: "white",
                textShadow: "0 0 2px black"
            }
        });

        tile.addChild(vCanvas);
        tile.addChild(label);

        tile.size.set(vCanvas.size.x * resolution_scale, vCanvas.size.y * resolution_scale)

        vContainer.addChild(tile);

    }

    return vContainer;
}
