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

/**
 *
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} width
 * @param {number} height
 * @param {number} x_offset
 * @param {number} y_offset
 * @param {number[]} data
 * @param {number[]} [data_range_y]
 */
export function canvas2d_plot_line_array(
    ctx,
    width,
    height,
    x_offset,
    y_offset,
    data,
    data_range_y
) {
    const point_count = data.length;

    let _data_range_y = data_range_y;

    if (_data_range_y === undefined) {
        _data_range_y = array_compute_min_max(data)
    }

    const [min, max] = _data_range_y;

    const value_span = max - min;
    const normalization_multiplier = value_span !== 0 ? 1 / value_span : 0;

    ctx.beginPath();
    if (point_count === 1) {
        ctx.moveTo(x_offset, height + y_offset);
        ctx.lineTo(x_offset + width, height + y_offset);
    } else {

        for (let i = 0; i < point_count; i++) {
            const value = data[i];
            const value_normalized = (value - min) * normalization_multiplier;

            const v = 1 - value_normalized;
            const u = i / (point_count - 1);

            const x = u * width + x_offset;
            const y = v * height + y_offset;

            if (i === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
    }
    ctx.stroke();
}
