import { assert } from "../assert.js";
import { gaussian } from "./gaussian.js";

/**
 * Build gaussian 2d kernel
 * @param {number[]|Float32Array} result
 * @param {number} samplesX
 * @param {number} samplesY
 * @param {number} sigma_x
 * @param {number} sigma_y
 */
export function build_gaussian_kernel_2d(
    result,
    samplesX, samplesY,
    sigma_x, sigma_y
) {
    assert.isNonNegativeInteger(samplesX, 'samplesX');
    assert.isNonNegativeInteger(samplesY, 'samplesY');

    const half_samples_x = (samplesX - 1) * 0.5;
    const half_samples_y = (samplesY - 1) * 0.5;

    let powerTotal = 0;
    let ix, iy;

    const i_samples_x = samplesX | 0;

    for (iy = 0; iy < samplesY; iy++) {
        const local_y = iy - half_samples_y;

        const fy = gaussian(sigma_y, local_y);

        for (ix = 0; ix < samplesX; ix++) {

            const local_x = ix - half_samples_x;

            const fx = gaussian(sigma_x, local_x);


            const power = fx * fy;

            powerTotal += power;

            result[iy * i_samples_x + ix] = power;
        }
    }

    const inv_total_power = 1 / powerTotal;

    // normalize kernel
    for (let i = 0; i < samplesX * samplesY; i++) {
        result[i] *= inv_total_power;
    }

}