Source: map/importer/utils.js

import { Layer } from "../layer/Layer/Layer.js";
import { Folder } from "../layer/Folder/Folder.js";

/**
 * Helper function to create a structure object for the layer tree.
 * optionally creates a new folder with the given name
 * 
 * @memberof vef.map.importer
 * @param {Layer[]} layers 
 * @param {string} folderName (optional) will be added to root as default
 * @param {string} parent (optional) default is '#'
 * 
 * @returns {object} {structure, layers}
 */
export function createLayerTreeStructure(layers, folderName, parent) {
    if (!Array.isArray(layers) || (layers.length == 0)) return { structure: {}, layers: {} };

    parent = (typeof parent == "string") ? parent : "#";

    const structure = {};
    const layerIDs = layers.map(layer => layer.uniqueId);
    const newLayers = layers.reduce((accumulator, layer) => {
        accumulator[layer.uniqueId] = layer;
        return accumulator;
    }, {});

    if (typeof folderName == "string") {
        const folder = new Folder({ title: folderName });
        structure[parent] = [folder.uniqueId];
        structure[folder.uniqueId] = layerIDs;
        newLayers[folder.uniqueId] = folder;
    } else {
        structure[parent] = layerIDs;
    }

    return {
        structure: structure,
        layers: newLayers
    };
}