import Vector2 from "../../../../../core/geom/Vector2.js";
import { max2 } from "../../../../../core/math/max2.js";
import LabelView from "../../../../../view/common/LabelView.js";
import { debug_draw_sampler } from "./debug_draw_sampler.js";

/**
 *
 * @param {Engine} engine
 * @param {Sampler2D} input
 * @param {function(Sampler2D,Sampler2D,{label:string, skip:boolean})[]} transforms
 * @param {Vector2} size
 * @param {boolean} display_labels
 */
export function debug_draw_sampler_grid({
                                            engine,
                                            input,
                                            transforms,
                                            size = new Vector2(input.width, input.height),
                                            display_labels = true
                                        }) {

    const GAP_SIZE = 4;

    let draw_index = 0;

    const viewport_width = window.innerWidth;
    const tiles_x = max2(1, Math.floor(viewport_width / (size.x + GAP_SIZE)));

    for (let i = 0; i < transforms.length; i++) {
        const out = input.clone();

        out.resize(size.x, size.y);

        const params = {
            label: '',
            skip: false
        };

        const t0 = performance.now();

        try {
            transforms[i](out, input, params);
        } catch (e) {
            // error, skip
            console.error(`Failed '${params.label}'. Reason: ${e.message}`)
            continue;
        }

        const t1 = performance.now();

        if (params.skip) {
            continue;
        }

        const t_duration = t1 - t0;

        console.log(`Executed ${params.label} in ${t_duration}ms`);


        const draw_x = (draw_index % tiles_x) * (size.x + GAP_SIZE);
        const draw_y = Math.floor(draw_index / tiles_x) * (size.y + GAP_SIZE);

        const view = debug_draw_sampler(engine, out, draw_x, draw_y);

        if (params.label.length > 0 && display_labels) {
            const vLabel = new LabelView(params.label, {
                css: {
                    position: 'absolute',
                    fontFamily: 'sans-serif',
                    fontWeight: 'bold',
                    top: 0,
                    left: 0,
                    zIndex: 1,
                    color: '#000000',
                    textShadow: '1px 1px 1px white',
                    background: 'rgba(255,255,255,0.7)',
                    padding: '2px'
                }
            });

            view.addChild(vLabel);
        }

        draw_index++;

    }

}

