import { BlendingType } from "./BlendingType.js";

/**
 *
 * @param {number[]} source
 * @param {number[]} destination
 * @param {Array} result
 */
function blendFunctionNormal(source, destination, result) {

    const a1 = source[3] / 255;
    const a0 = destination[3] / 255;

    result[0] = source[0] * a1 + destination[0] * (1 - a1);
    result[1] = source[1] * a1 + destination[1] * (1 - a1);
    result[2] = source[2] * a1 + destination[2] * (1 - a1);
    result[3] = (a1 + a0 * (1 - a1)) * 255;
}

/**
 * Assumes both samplers are RGBA uint8 with values 0-255
 * @param {Sampler2D} destination
 * @param {Sampler2D} source
 * @param {number} sourceX
 * @param {number} sourceY
 * @param {number} destinationX
 * @param {number} destinationY
 * @param {number} width
 * @param {number} height
 * @param {BlendingType} [blendMode]
 */
export function sampler2d_paint(
    destination,
    source,
    sourceX, sourceY,
    destinationX, destinationY,
    width, height,
    blendMode = BlendingType.Normal
) {

    let blendFunction;
    if (blendMode === BlendingType.Normal) {
        blendFunction = blendFunctionNormal;
    } else {
        throw new Error(`Unsupported blendType(=${blendMode})`);
    }

    const _w = Math.min(width, source.width - sourceX, destination.width - destinationX);
    const _h = Math.min(height, source.height - sourceY, destination.height - destinationY);

    const _x0 = Math.max(0, -destinationX);
    const _y0 = Math.max(0, -destinationY);

    const c0 = [0, 0, 0, 255];
    const c1 = [0, 0, 0, 255];

    const c3 = [];

    let x, y;

    for (y = _y0; y < _h; y++) {
        for (x = _x0; x < _w; x++) {
            const d_x = Math.round(x + destinationX);
            const d_y = Math.round(y + destinationY);

            destination.read(d_x, d_y, c0);

            const s_x = Math.round(x + sourceY);
            const s_y = Math.round(y + sourceY);

            source.read(s_x, s_y, c1);

            blendFunction(c1, c0, c3);

            destination.write(d_x, d_y, c3);

        }
    }


}