//

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

/**
 *
 * @param {number[]|Float32Array} output
 * @param {number} output_offset
 * @param {number[]|Float32Array} input
 * @param {number} input_offset
 * @param {number} input_size
 */
export function downsample_float_array(output, output_offset, input, input_offset, input_size) {
    assert.isNonNegativeInteger(output_offset, 'output_offset');
    assert.isNonNegativeInteger(input_offset, 'input_offset');
    assert.isNonNegativeInteger(input_size, 'input_size');

    const target_samples = input_size / 2;

    if (!Number.isInteger(target_samples)) {
        throw new Error(`input_size(=${input_size}) is not divisible by 2`);
    }

    if (target_samples === 1) {
        // special case, take average
        output[output_offset] = (
            input[input_offset] + input[input_offset + 1]
        ) / 2;

        return;
    }

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

        const f = i / (target_samples - 1);

        const input_sample_offset = input_offset + i * 2;

        const s0 = input[input_sample_offset];
        const s1 = input[input_sample_offset + 1];

        const sample_value = lerp(s0, s1, f);

        // TODO implement decision scheme that would pick between min/max/average

        output[output_offset + i] = sample_value;
    }
}
