package ru.yandex.webmaster3.core.solomon.metric;

import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;

/**
 * @author avhaliullin
 */
public abstract class SolomonCounterImpl implements SolomonCounter, LongSupplier {

    private static class ThreadSafeImpl extends SolomonCounterImpl {
        private final AtomicLong counter = new AtomicLong(0L);

        @Override
        public void add(long value) {
            counter.addAndGet(value);
        }

        @Override
        public long get() {
            return counter.get();
        }

        @Override
        public long getAsLong() {
            return get();
        }
    }

    private static class NonThreadSafeImpl extends SolomonCounterImpl {
        private long value = 0L;

        @Override
        public void add(long value) {
            this.value += value;
        }

        @Override
        public long get() {
            return value;
        }

        @Override
        public long getAsLong() {
            return get();
        }
    }

    public static SolomonCounterImpl create(boolean threadSafe) {
        return threadSafe ? new ThreadSafeImpl() : new NonThreadSafeImpl();
    }
}
