package ru.yandex.qe.cache.telemetry;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.monlib.metrics.registry.MetricRegistry;

/**
 * @author lvovich
 */
public class ConfigurableCacheFactoryBean implements FactoryBean<Ehcache> {

    private final MetricRegistry metricRegistry;

    private CacheConfiguration cacheConfiguration;

    private boolean telemetryEnabled;

    public ConfigurableCacheFactoryBean(MetricRegistry metricRegistry) {
        this.metricRegistry = metricRegistry;
    }

    @Required
    public void setCacheConfiguration(final CacheConfiguration cacheConfiguration) {
        this.cacheConfiguration = cacheConfiguration;
    }

    @Required
    public void setTelemetryEnabled(final boolean telemetryEnabled) {
        this.telemetryEnabled = telemetryEnabled;
    }

    @Override
    public Ehcache getObject() throws Exception {
        final Cache plainCache = new Cache(cacheConfiguration);
        if (telemetryEnabled) {
            return new MetricsInstrumentedCache(plainCache, metricRegistry);
        } else {
            return plainCache;
        }
    }

    @Override
    public Class<?> getObjectType() {
        return Ehcache.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
