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

/**
 *
 * @param {Sampler2D} sampler
 * @param {number} [channel=0]
 * @returns {undefined|{x: number, index:number, y: number, value: number}}
 */
export function sampler2d_channel_compute_min(sampler, channel=0){
    const itemSize = sampler.itemSize;

    assert.isNumber(channel, "channel");
    assert.isNonNegativeInteger(channel , 'channel');
    assert.lessThan(channel, itemSize, `channel must be less than itemSize(=${itemSize}), was ${channel}`);

    const data = sampler.data;

    const l = data.length;

    if (l === 0) {
        //no data
        return undefined;
    }

    let bestValue = data[channel];
    let bestIndex = channel;

    for (let i = channel + itemSize; i < l; i += itemSize) {
        const value = data[i];

        if (bestValue > value) {
            bestValue = value;
            bestIndex = i;
        }

    }

    const width = sampler.width;

    const itemIndex = (bestIndex / itemSize) | 0;

    const x = itemIndex % width;
    const y = (itemIndex / width) | 0;

    return {
        index: bestIndex,
        value: bestValue,
        x,
        y
    };
}
