import { Cache } from "../core/cache/Cache.js";
import { combine_hash } from "../core/collection/array/combine_hash.js";
import { computeMaterialEquality } from "../engine/asset/loaders/material/computeMaterialEquality.js";
import { computeMaterialHash } from "../engine/asset/loaders/material/computeMaterialHash.js";
import { makeMaterialIcon } from "./makeMaterialIcon.js";


/**
 * @typedef {Object} CacheKey
 * @property {number} size
 * @property {Material} material
 */

/**
 *
 * @type {Cache<CacheKey, Sampler2D>}
 */
const cache = new Cache({
                            maxWeight: 1024000,
                            valueWeigher(value) {
                                return value.computeByteSize();
                            },
                            keyHashFunction(key) {
                                return combine_hash(
                                    key.size,
                                    computeMaterialHash(key.material)
                                )
                            },
                            keyEqualityFunction(a, b) {
                                return a.size === b.size
                                       && computeMaterialEquality(a.material, b.material);
                            }
                        });

/**
 *
 * @param {Material} material
 * @param {WebGLRenderer} [renderer]
 * @param {number} [size]
 * @returns {Sampler2D}
 */
export function makeMaterialIconCached(material, renderer, size) {
    const key = {
        material,
        size
    };

    let sampler = cache.get(key);

    if (sampler === null) {
        sampler = makeMaterialIcon(material, renderer, size);

        cache.put(key, sampler);
    }

    return sampler;
}
