package de.renew.net;

import de.renew.engine.thread.SimulationThreadPool;

/**
 * A class containing some helper methods that don't appear to be used.
 */
public class EventHelper {

    /**
     * Finds a place by its name in a {@link Net}.
     *
     * @param net the net to look for the place in
     * @param name the name of the place that should be returned
     * @return the place with that name, or null if no place with that name has been found
     */
    public static Place getNamedPlace(Net net, String name) {
        assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread";

        synchronized (net) {
            return net.places().stream().filter(place -> name.equals(place.getName())).findFirst()
                .orElse(null);
        }
    }

    /**
     * Deposits a token in a place identified by its name (in a {@link NetInstance}).
     *
     * @param netInstance the net instance that the place is located in
     * @param name the name of the place to deposit the token in
     * @param token the token to deposit
     * @throws RuntimeException if no place with the given name exists
     */
    public static void deposit(NetInstance netInstance, String name, Object token) {
        assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread";

        Place place = getNamedPlace(netInstance.getNet(), name);
        if (place == null) {
            throw new RuntimeException("No such place: " + name);
        }

        SimulatablePlaceInstance placeInstance =
            (SimulatablePlaceInstance) netInstance.getInstance(place);
        placeInstance._lock.lock();
        try {
            placeInstance.insertToken(token, 0);
        } finally {
            placeInstance._lock.unlock();
        }
    }
}