/*
 * Copyright © 2012-2024 by Data Virtuality GmbH
 */
package org.teiid.dqp.internal.process;

import com.datavirtuality.dv.core.interfaces.DVCache;
import org.teiid.cache.Cache;
import org.teiid.cache.MapCache;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Roman Pedchenko
 * @date 2024.07.29
 */
public class DQPRunningCount {
        private Cache<String, AtomicInteger> cache;

        public synchronized void init(DQPCore dqpCore) {
            cache = dqpCore.getDvCache(DVCache.QUERIES_RUNNING_COUNT);
            if (cache == null)
                cache = new MapCache<>("map-queries-running-count");
        }

        public synchronized Integer get(String id) {
            final AtomicInteger i = cache.get(id);
            if (i == null)
                return 0;
            return i.get();
        }

        public synchronized void reset(String id) {
            final AtomicInteger i = cache.get(id);
            if (i != null)
                i.set(0);
        }

        public synchronized void remove(String id) {
            cache.remove(id);
        }

        public synchronized void inc(String id) {
            final AtomicInteger i = cache.get(id);
            if (i == null)
                cache.put(id, new AtomicInteger(1), null);
            else
                i.incrementAndGet();
        }

        public synchronized void dec(String id) {
            final AtomicInteger i = cache.get(id);
            if (i != null)
                i.decrementAndGet();
        }

        public synchronized void clear() {
            cache.clear();
        }
}
