/**
 * Creates a Mesh Depth Material, which can be extended with GL nodes.
 *
 * @remarks
 * This node can create children, which will be GL nodes. The GLSL code generated by the nodes will extend the Material.
 *
 */
import {NodeParamsConfig} from '../utils/params/ParamsConfig';
import {
	UniformsTransparencyParamConfig,
	UniformsTransparencyController,
	UniformsTransparencyControllers,
} from './utils/UniformsTransparencyController';
import {
	AdvancedCommonController,
	AdvancedCommonControllers,
	AdvancedCommonParamConfig,
} from './utils/AdvancedCommonController';
import {BaseBuilderParamConfig, TypedBuilderMatNode} from './_BaseBuilder';
import {AssemblerName} from '../../poly/registers/assemblers/_BaseRegister';
import {Poly} from '../../Poly';
import {Material} from 'three';
import {MeshDistanceMaterial} from 'three';
import {CustomMaterialName, IUniforms} from '../../../core/geometry/Material';
import {ShaderAssemblerCustomMeshDistance} from '../gl/code/assemblers/materials/custom/mesh/CustomMeshDistance';
import {MatType} from '../../poly/registers/nodes/types/Mat';
interface MeshDistanceBuilderControllers extends AdvancedCommonControllers, UniformsTransparencyControllers {}
interface MeshDistanceBuilderMaterial extends MeshDistanceMaterial {
	vertexShader: string;
	fragmentShader: string;
	uniforms: IUniforms;
	customMaterials: {
		[key in CustomMaterialName]?: Material;
	};
}

class MeshDistanceBuilderMatParamsConfig extends AdvancedCommonParamConfig(
	BaseBuilderParamConfig(UniformsTransparencyParamConfig(NodeParamsConfig))
) {}
const ParamsConfig = new MeshDistanceBuilderMatParamsConfig();

export class MeshDistanceBuilderMatNode extends TypedBuilderMatNode<
	MeshDistanceBuilderMaterial,
	ShaderAssemblerCustomMeshDistance,
	MeshDistanceBuilderMatParamsConfig
> {
	override paramsConfig = ParamsConfig;
	static override type() {
		return MatType.MESH_DISTANCE_BUILDER;
	}
	public override usedAssembler(): Readonly<AssemblerName.GL_MESH_DISTANCE> {
		return AssemblerName.GL_MESH_DISTANCE;
	}
	protected _createAssemblerController() {
		return Poly.assemblersRegister.assembler(this, this.usedAssembler());
	}
	public override customMaterialRequested(customName: CustomMaterialName): boolean {
		return false;
	}

	readonly controllers: MeshDistanceBuilderControllers = {
		advancedCommon: new AdvancedCommonController(this),
		uniformTransparency: new UniformsTransparencyController(this),
	};
	protected override controllersList = Object.values(this.controllers);

	override async cook() {
		this._material = this._material || this.createMaterial();
		await Promise.all(this.controllersPromises(this._material));

		this.compileIfRequired(this._material);

		this.setMaterial(this._material);
	}
}
