package com.eactive.eai.rms.common.cache.jpa.ehcache;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import com.eactive.eai.rms.common.cache.jpa.NativeCacheCleaner;

@Service
public class EhcacheCacheCleanerImpl implements NativeCacheCleaner {

	private EhCacheCacheManager ehCacheCacheManager;

	@Autowired
	public EhcacheCacheCleanerImpl(EhCacheCacheManager ehCacheCacheManager) {
		this.ehCacheCacheManager = ehCacheCacheManager;
	}

	@Override
	public Collection<String> findCacheNames() {
		return ehCacheCacheManager.getCacheNames().stream().sorted().collect(Collectors.toSet());
	}

	@Override
	public void clear() {
		net.sf.ehcache.CacheManager nativeCacheManager = ehCacheCacheManager.getCacheManager();
		if (nativeCacheManager == null) {
			return;
		}

		String[] cacheNames = nativeCacheManager.getCacheNames();
		for (String cacheName : cacheNames) {
			clear(cacheName);
		}
	}

	@Override
	public void clear(String cacheName) {
		net.sf.ehcache.CacheManager nativeCacheManager = ehCacheCacheManager.getCacheManager();
		if (nativeCacheManager != null) {
			net.sf.ehcache.Cache cache = nativeCacheManager.getCache(cacheName);
			if (cache != null) {
				cache.removeAll();
			}
		}
	}

}
