import { array_compute_min_max } from "../../../../core/collection/array/array_compute_min_max.js";
import Vector2 from "../../../../core/geom/Vector2.js";
import { CanvasView } from "../../../../view/elements/CanvasView.js";
import Entity from "../../../ecs/Entity.js";
import GUIElement from "../../../ecs/gui/GUIElement.js";
import ViewportPosition from "../../../ecs/gui/position/ViewportPosition.js";
import { canvas2d_draw_label } from "../../../graphics/canvas/canvas2d_draw_label.js";
import { canvas2d_plot_data_line } from "../../../graphics/canvas/canvas2d_plot_data_line.js";

/**
 *
 * @param {number[]} data
 * @param {number} x
 * @param {number} y
 * @param {number} [width]
 * @param {number} [height]
 * @param {Vector2} [margin]
 * @param {string} [label]
 * @return {Entity}
 */
export function build_plot_entity_from_array({
                                                 data,
                                                 x, y,
                                                 width = 600,
                                                 height = 200,
                                                 margin = new Vector2(10, 10),
                                                 label = ''
                                             }) {

    const canvasView = new CanvasView();
    canvasView.size.set(width, height);
    canvasView.css({
        position: "absolute",
        left: "0",
        top: "0"
    });
    const ctx = canvasView.context2d;

    canvas2d_plot_data_line({ ctx, data, width, height, margin, range_x: [0, 1], range_y: array_compute_min_max(data) });

    const text = `${data.length}`;
    canvas2d_draw_label({
        ctx: ctx,
        text: text,
        x: margin.x,
        y: height - (20),
        fontSize: 20,
        color: 'red'
    });

    if (typeof label === "string" && label.length > 0) {
        canvas2d_draw_label({ ctx: ctx, text: label, x: width - margin.x - 50, y: 20 })
    }

    return new Entity()
        .add(ViewportPosition.fromJSON({
            offset: { x, y }
        }))
        .add(GUIElement.fromView(canvasView));
}
