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

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManagerFactory;

import org.hibernate.SessionFactory;
import org.hibernate.cache.spi.CacheImplementor;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

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

@Service
public class HibernateCacheCleaner implements JpaCacheCleaner {

	private EntityManagerFactory entityManagerFactory;
	private EntityManagerFactory entityManagerFactoryForEMS;

	@Autowired
	public HibernateCacheCleaner(EntityManagerFactory entityManagerFactory,
			@Qualifier("entityManagerFactoryForEMS") EntityManagerFactory entityManagerFactoryForEMS) {
		this.entityManagerFactory = entityManagerFactory;
		this.entityManagerFactoryForEMS = entityManagerFactoryForEMS;
	}

	@Override
	public Collection<String> findCacheNames() {

		Set<String> names = new HashSet<>();

		String[] olnNames = entityManagerFactory
				.unwrap(SessionFactory.class)
				.getStatistics()
				.getSecondLevelCacheRegionNames();

		String[] manNames = entityManagerFactoryForEMS
				.unwrap(SessionFactory.class)
				.getStatistics()
				.getSecondLevelCacheRegionNames();

		names.addAll(Arrays.asList(olnNames));
		names.addAll(Arrays.asList(manNames));

		return names;
	}

	@Override
	public void clear() {
		entityManagerFactory.getCache().evictAll();
		entityManagerFactoryForEMS.getCache().evictAll();
	}

	@Override
	public void clear(String cacheRegionName) {
		CacheImplementor cacheImplementor = ((SessionFactoryImpl) entityManagerFactory.unwrap(SessionFactory.class))
				.getCache();
		cacheImplementor.evictRegion(cacheRegionName);

		CacheImplementor cacheImplementorForEMS = ((SessionFactoryImpl) entityManagerFactoryForEMS
				.unwrap(SessionFactory.class)).getCache();
		cacheImplementorForEMS.evictRegion(cacheRegionName);
	}

}
