package org.ghidra.bridge.session;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

public final class HandleRegistry<T> {
    private final AtomicLong nextHandle = new AtomicLong(1);
    private final Map<Long, T> values = new HashMap<>();
    private final Class<T> type;

    public HandleRegistry(Class<T> type) {
        this.type = type;
    }

    public synchronized long insert(T value) {
        long handle = nextHandle.getAndIncrement();
        values.put(handle, value);
        return handle;
    }

    public synchronized T get(long handle) {
        T value = values.get(handle);
        if (value == null) {
            throw new IllegalArgumentException("invalid " + type.getSimpleName() + " handle " + handle);
        }
        return value;
    }

    public synchronized T remove(long handle) {
        T value = values.remove(handle);
        if (value == null) {
            throw new IllegalArgumentException("invalid " + type.getSimpleName() + " handle " + handle);
        }
        return value;
    }
}
