import {build_three_object} from "../build_three_object.js";
import {ShadedGeometry} from "../ShadedGeometry.js";

class CacheValue {
    object = null
    key = null
}


export class SGThreeObjectCache {
    constructor() {
        /**
         *
         * @type {Map<ShadedGeometry, CacheValue>}
         * @private
         */
        this.__object_cache = new WeakMap();
    }

    /**
     *
     * @param {ShadedGeometry} sg
     * @returns {THREE.Object3D}
     */
    get(sg) {

        const existing_value = this.__object_cache.get(sg);

        if (existing_value !== undefined) {
            const object = existing_value.object;

            // validate that the object is still the same
            if (existing_value.key.equals(sg)) {
                return object;
            } else {
                // object has changed, dispose of cached version and let it be rebuilt
                // object.dispose();
            }
        }

        // replace scratch key as it's being used inside the cache now
        const key = sg.clone();

        const new_object = build_three_object(key);

        const cacheValue = new CacheValue();

        cacheValue.key = key;
        cacheValue.object = new_object;

        this.__object_cache.set(sg, cacheValue);

        return new_object;
    }
}

/**
 * @readonly
 * @type {SGThreeObjectCache}
 */
SGThreeObjectCache.INSTANCE = new SGThreeObjectCache();
