import { MeshMatcapMaterial } from "three";
import sampler2d_to_html_canvas from "../engine/graphics/texture/sampler/sampler2d_to_html_canvas.js";
import { RadialMenuElementDefinition } from "../view/elements/radial/RadialMenuElementDefinition.js";
import View from "../view/View.js";
import { makeMaterialIconCached } from "./makeMaterialIconCached.js";

/**
 *
 * @param {string} texture
 * @param {AssetManager} assetManager
 * @param {THREE.WebGLRenderer} [renderer]
 * @param {number} [iconSize]
 * @returns {RadialMenuElementDefinition}
 */
export async function makeMatcapSelectionOption(
    {
        texture,
        assetManager,
        renderer,
        label = "",
        iconSize = 32
    }
) {
    const texture_asset = await assetManager.promise(texture, "texture");
    const texture_object = texture_asset.create();
    //
    const material = new MeshMatcapMaterial({
                                                matcap: texture_object
                                            });

    const icon = makeMaterialIconCached(material, renderer, iconSize);

    // cleanup material and texture memory
    material.dispose();
    texture_object.dispose();

    const canvasElement = sampler2d_to_html_canvas(icon, 1, 0);

    const icon_view = new View();
    icon_view.el = canvasElement;

    const pixel = [];
    icon.sampleBicubicUV(0.7, 0.7, pixel);

    return RadialMenuElementDefinition.from({
                                                iconView: icon_view,
                                                iconSize: iconSize,
                                                fill: `rgba(${pixel[0]},${pixel[1]},${pixel[2]},0.6)`,
                                                name: label,
                                                nameFill: "white"
                                            });
}
