import { typed_array_is_integer } from "../../../../core/collection/array/typed/typed_array_is_integer.js";

/**
 * Applies a linear polynomial transform to each value of a given channel
 * @param {Sampler2D} output
 * @param {Sampler2D} input
 * @param {number} output_channel_index
 * @param {number} input_channel_index
 * @param {number} gradient
 * @param {number} intercept
 */
export function sampler2d_channel_linear_transform(
    output, input,
    output_channel_index, input_channel_index,
    gradient, intercept
) {

    const input_width = input.width;
    const input_height = input.height;

    const output_width = output.width;
    const output_height = output.height;

    if (
        input_width !== output_width
        || input_height !== output_height
    ) {
        throw new Error('Dimensions of input and output are incompatible');
    }

    const input_item_size = input.itemSize;
    const output_item_size = output.itemSize;

    const input_data = input.data;
    const output_data = output.data;

    const pixel_count = input_width * input_height;


    if (typed_array_is_integer(output_data)) {

        for (let i = 0; i < pixel_count; i++) {

            const input_address = i * input_item_size + input_channel_index;
            const output_address = i * output_item_size + output_channel_index;

            const input_value = input_data[input_address];

            output_data[output_address] = Math.round(input_value * gradient + intercept);

        }

    } else {

        for (let i = 0; i < pixel_count; i++) {

            const input_address = i * input_item_size + input_channel_index;
            const output_address = i * output_item_size + output_channel_index;

            const input_value = input_data[input_address];

            output_data[output_address] = input_value * gradient + intercept;

        }

    }

}
