import { CubeUVReflectionMapping, Texture } from "three";
import { type GLTFLoaderPlugin, GLTFParser } from "three/examples/jsm/loaders/GLTFLoader.js";

import { getParam } from "../engine_utils.js";


const debug = getParam("debugexr") || getParam("debugpmrem");

export class NEEDLE_pmrem implements GLTFLoaderPlugin {
	get name() { return "NEEDLE_pmrem" }

	private parser: GLTFParser;

	constructor(parser: GLTFParser) {
		this.parser = parser;
	}

	loadTexture(textureIndex: number): Promise<Texture> | null {

		const name = this.name;
		const parser = this.parser;
		const json = parser.json;

		const textureDef = json.textures[textureIndex];

		if (!textureDef.extensions || !textureDef.extensions[name]) {
			return null;
		}

		const extension = textureDef.extensions[name];

		// Use the KTX2Loader already configured on the GLTFLoader (with GPU support detection)
		const loader = (parser.options as any).ktx2Loader;
		if (!loader) {
			console.warn("NEEDLE_pmrem: No KTX2Loader available on GLTFLoader — cannot load PMREM texture");
			return null;
		}

		if (debug) console.log("NEEDLE_pmrem.loadTexture", textureIndex, extension);

		const promise = parser.loadTextureImage(textureIndex, extension.source, loader);
		return promise.then(tex => {
			NEEDLE_pmrem.postprocess(tex);
			tex.name = "PMREM_" + tex.name;
			if (debug) console.log("NEEDLE_pmrem: loaded PMREM texture", tex);
			return tex;
		});
	}

	static postprocess(tex: Texture) {
		tex.mapping = CubeUVReflectionMapping;
		return tex;
	}
}