import { addCustomExtensionPlugin } from "@needle-tools/engine";
import { Context, GLTF, INeedleGLTFExtensionPlugin } from "@needle-tools/engine";
import type { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import type { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
import { useNeedleMaterialX as _useNeedleMaterialX, MaterialXLoader } from "./loader.three.js";
import { debug } from "../utils.js";
import { MaterialParameters } from "three";


export class MaterialXLoaderPlugin implements INeedleGLTFExtensionPlugin {
    readonly name = "MaterialXLoaderPlugin";

    private loader: MaterialXLoader | null = null;

    onImport = (loader: GLTFLoader, url: string, context: Context) => {
        if (debug) console.log("MaterialXLoaderPlugin: Registering MaterialX extension for", url);
        _useNeedleMaterialX(loader, {
            cacheKey: url,
            parameters: {
                precision: context.renderer.capabilities.getMaxPrecision("highp") as MaterialParameters["precision"],
            }
        }, {
            getTime: () => context.time.time,
            getFrame: () => context.time.frame,
        });
    };

    onLoaded = (url: string, gltf: GLTF, _context: Context) => {
        if (debug) console.log("[MaterialX] MaterialXLoaderPlugin: glTF loaded", { url, scene: gltf.scene, materialX_root_data: this.loader?.materialX_root_data });
    };

    onExport = (_exporter: GLTFExporter, _context: Context) => {
        console.warn("[MaterialX] Export is not supported");
    };
}


/**
 * Add the MaterialXLoaderPlugin to the Needle Engine.
 */
export async function useNeedleMaterialX() {
    addCustomExtensionPlugin(new MaterialXLoaderPlugin());
}