package de.renew.net;

import java.io.Serializable;

/**
 * The {@code IDCounter} class represents a reference counter associated with a unique ID.
 * It is used to track the number of reservations that exist for a given ID, so that it can be discarded
 * when no longer needed.
 */
class IDCounter implements Serializable {
    /**
     * The unique identifier managed by this counter.
     */
    private final String _id;
    /**
     * The number of active reservations for this ID.
     */
    private int _reserves;

    /**
     * Constructs a new {@code IDCounter} with the specified ID and
     * initializes the reservation counter to zero.
     *
     * @param id the unique identifier to be managed
     */
    IDCounter(String id) {
        _id = id;
        _reserves = 0;
    }

    /**
     * Returns the ID associated with this counter.
     *
     * @return the managed ID string
     */
    String getID() {
        return _id;
    }

    /**
     * Increments the reservation count by one.
     */
    void reserve() {
        _reserves++;
    }

    /**
     * Increments the reservation count by the specified number.
     *
     * @param n the number of reservations to add
     */
    void reserve(int n) {
        _reserves += n;
    }

    /**
     * Decrements the reservation count by one.
     */
    void unreserve() {
        _reserves--;
    }

    /**
     * Checks whether this ID can be discarded, i.e., whether there
     * are no active reservations.
     *
     * @return {@code true} if the reservation count is zero, {@code false} otherwise
     */
    boolean isDiscardable() {
        return _reserves == 0;
    }
}