import { assert } from "../../../../core/assert.js";

let id_counter = 0;

/**
 * @template T
 */
export class ResourceEntry {
    /**
     *
     * @type {number}
     */
    resource_id = id_counter++;

    /**
     *
     * @type {ResourceDescriptor<T>|null}
     */
    resource_descriptor = null;

    /**
     * Every time resource is modified - version increases
     * @type {number}
     */
    resource_version = 0;

    /**
     * Actual resource handle
     * @type {T|null}
     */
    resource = null;

    /**
     * Imported or transient resource.
     * Transient resource only exists in the graph, it will be reclaimed once the execution is done
     * @type {boolean}
     */
    imported = false;

    /**
     * Node that created this resource
     * @type {FramePassNode|null}
     */
    producer = null;

    /**
     *
     * @type {FramePassNode|null}
     */
    last = null;

    /**
     * Creates actual resource
     * @param {RenderResourceManager} resources
     */
    create(resources) {
        assert.ok(this.isTransient(), 'Only transient resources can be allocated');

        this.resource = resources.get(this.resource_descriptor)
    }

    /**
     * De-allocated memory for the resource
     * @param {RenderResourceManager} resources
     */
    destroy(resources) {
        assert.ok(this.isTransient(), 'Only transient resources can be destroyed, that is resources that are created by the graph itself');

        resources.release(this.resource);
    }

    /**
     *
     * @return {boolean}
     */
    isImported() {
        return this.imported;
    }

    /**
     *
     * @return {boolean}
     */
    isTransient() {
        return !this.imported;
    }

    toString() {
        if (this.resource_descriptor !== null) {

            return this.resource_descriptor.toString();

        }

        return "";
    }
}
