

import { Context, GLTF, addCustomExtensionPlugin, 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 { MaterialXLoader } from "./loader.three.js";
import { debug } from "../utils.js";

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);

        // Register the MaterialX loader extension
        // Environment initialization is now handled in the MaterialXLoader constructor
        loader.register(p => {
            this.loader = new MaterialXLoader(p, url, {
                getTime: () => context.time.time,
                getFrame: ()=> context.time.frame,
                getScene: () => context.scene,
                getRenderer: () => context.renderer,
            });
            return this.loader;
        });
    };

    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 });

        // If we don't have MaterialX data in the loaded glTF we don't need to do anything else here
        if (!this.loader?.materialX_root_data) {
            return;
        }

        if (debug) console.log("[MaterialX] Loaded: ", this.loader);


    };

    onExport = (_exporter: GLTFExporter, _context: Context) => {
        console.warn("[MaterialX] Export is not supported");
        // TODO: Add MaterialX export functionality if needed
    };
}

export function registerNeedleLoader() {
    addCustomExtensionPlugin(new MaterialXLoaderPlugin());
}
