import { Texture } from "three";
import { GridTransformKind } from "../../../../../../src/engine/ecs/terrain/ecs/GridTransformKind.js";
import { TerrainFlags } from "../../../../../../src/engine/ecs/terrain/ecs/TerrainFlags.js";
import { BitFlagsEditor } from "../../common/BitFlagsEditor.js";
import { EnumEditor } from "../../common/EnumEditor.js";
import { ObjectEditor } from "../../primitive/ObjectEditor.js";

export class TerrainEditor extends ObjectEditor {
    build(parent, field, registry) {
        const view = super.build(parent, field, registry);

        if (view) {

            /**
             * @type {Terrain}
             */
            const terrain = field.adapter.read(parent, field.name);

            function updateLayers() {

                terrain.layers.buildTexture();
                terrain.layers.writeAllLayersDataIntoTexture();

                terrain.updateMaterial();
            }

            // splats
            view.bindSignal(terrain.layers.layers.on.added, () => {
                if (terrain.getFlag(TerrainFlags.Built)) {
                    terrain.splat.addWeightLayer();
                    updateLayers();
                }
            });
            view.bindSignal(terrain.layers.layers.on.removed, (a, index) => {
                if (terrain.getFlag(TerrainFlags.Built)) {
                    terrain.splat.removeWeightLayer(index);

                    updateLayers();
                }
            });

            // mapping sizes
            view.bindSignal(terrain.splat.size.onChanged, (x, y) => {
                if (terrain.getFlag(TerrainFlags.Built)) {
                    terrain.splat.resize(x, y, terrain.splat.depth);

                    terrain.updateMaterial();
                }
            });
        }

        return view;
    }

    get schema() {
        return {
            properties: {
                id: {
                    transient: true
                },
                flags: {
                    editor: new BitFlagsEditor(TerrainFlags),
                    transient: true
                },
                gridTransformKind: {
                    editor: new EnumEditor(GridTransformKind)
                },
                material: {
                    transient: true
                },
                heightRange: {
                    deprecated: true
                },
                bvh: {
                    transient: true,
                },
                heightTexture: {
                    transient: true
                },
                buildLightMap: {
                    type: Function
                },
                aoMap: {
                    type: Texture
                }
            }
        };
    }
}
