import Vector2 from "../../../../src/core/geom/Vector2.js";
import ObservedValue from "../../../../src/core/model/ObservedValue.js";
import { sampler2d_scale } from "../../../../src/engine/graphics/texture/sampler/resize/sampler2d_scale.js";
import { Sampler2D } from "../../../../src/engine/graphics/texture/sampler/Sampler2D.js";
import sampler2d_to_html_canvas from "../../../../src/engine/graphics/texture/sampler/sampler2d_to_html_canvas.js";
import { CanvasView } from "../../../../src/view/elements/CanvasView.js";
import View from "../../../../src/view/View.js";
import DatGuiController from "./DatGuiController.js";

/**
 *
 * @param {GridObstacle} grid
 * @param {HTMLCanvasElement} canvas
 */
export function buildGridObstaclePreview(grid, canvas) {
    const source = new Sampler2D(grid.data, 1, grid.size.x, grid.size.y);

    const target = Sampler2D.uint8(1, canvas.width, canvas.height);

    sampler2d_scale(source, target);

    sampler2d_to_html_canvas(target, 255, 0, canvas);
}

export class GridObstacleController extends View {
    constructor() {
        super();

        this.el = document.createElement('div');

        this.model = new ObservedValue(null);

        const self = this;

        /**
         *
         * @param {GridObstacle} model
         */
        function setModel(model) {
            self.removeAllChildren();

            const vPreview = new CanvasView();

            vPreview.size.set(200, 200);

            buildGridObstaclePreview(model, vPreview.el);

            self.addChild(vPreview);

            const controller = new DatGuiController();

            self.addChild(controller);

            const proxy = {
                size: new Vector2(model.size.x, model.size.y)
            };

            controller.add(proxy, 'size');
            controller.addAction(() => {
                buildGridObstaclePreview(model, vPreview.el);
            }, 'update preview');

            proxy.size.onChanged.add((x, y) => {
                model.resize(x, y);

                buildGridObstaclePreview(model, vPreview.el);
            });
        }

        this.model.onChanged.add(setModel);
    }
}
