import { BufferGeometry } from "three";
import { buffer_attribute_deinterleave } from "./buffer_attribute_deinterleave.js";

/**
 *
 * @param {THREE.BufferGeometry} geometry
 * @returns {THREE.BufferGeometry}
 */
export function deinterleaveBufferGeometry(geometry) {
    const result = new BufferGeometry();

    if (geometry.getIndex() !== null) {
        result.setIndex(buffer_attribute_deinterleave(geometry.getIndex()));
    }

    for (const attribute_key in geometry.attributes) {
        const source_attribute = geometry.attributes[attribute_key];

        result.setAttribute(attribute_key, buffer_attribute_deinterleave(source_attribute));
    }

    // copy other bits
    result.name = geometry.name;

    result.morphTargetsRelative = geometry.morphTargetsRelative;

    for (const attribute_key in geometry.morphAttributes) {
        const source_attributes = geometry.morphAttributes[attribute_key];

        const result_attributes = [];

        result.morphAttributes[attribute_key] = result_attributes;

        for (let i = 0; i < source_attributes.length; i++) {
            const source_attribute = source_attributes[i];
            result_attributes[i] = buffer_attribute_deinterleave(source_attribute);
        }
    }

    result.groups = geometry.groups.slice();


    result.boundingBox = geometry.boundingBox !== null ? geometry.boundingBox.clone() : null;
    result.boundingSphere = geometry.boundingSphere !== null ? geometry.boundingSphere.clone() : null;
    result.drawRange.start = geometry.drawRange.start;
    result.drawRange.count = geometry.drawRange.count;
    result.userData = JSON.parse(JSON.stringify(geometry.userData));

    return result;
}
