import { Reference } from "../../../reference/v2/Reference.js";
import Signal from "../../../../core/events/signal/Signal.js";

export class ManagedMaterial {

    /**
     *
     * @param {Material} m
     */
    constructor(m) {
        /**
         *
         * @type {Material|null}
         * @private
         */
        this.__source = null;

        /**
         *
         * @type {Material}
         * @private
         */
        this.__material = m;

        /**
         *
         * @type {number}
         * @private
         */
        this.__ref_count = 0;

        /**
         *
         * @type {Signal}
         */
        this.onLastReleased = new Signal();
    }

    getSource() {
        return this.__source;
    }

    setSource(v) {
        this.__source = v;
    }

    /**
     *
     * @returns {Material}
     */
    getMaterial() {
        return this.__material;
    }

    __release_reference() {
        this.__ref_count--;

        if (this.__ref_count === 0) {
            this.onLastReleased.send1(this);
        }
    }

    /**
     *
     * @returns {Reference<Material>}
     */
    getRef() {
        const reference = new Reference();

        reference.bind(this.__material);

        reference.onReleased.add(this.__release_reference, this);

        this.__ref_count++;

        return reference;
    }
}
