package me.chyxion.tigon.mybatis.cache.support;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import javax.annotation.PostConstruct;
import org.apache.ibatis.session.Configuration;
import me.chyxion.tigon.mybatis.cache.CacheTool;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Aug 26, 2015 10:58:58 AM
 */
@Slf4j
public class CacheToolSupport implements CacheTool {

    @Autowired
    private SqlSessionFactory ssf;
    private Configuration configuration;

    /**
     * {@inheritDoc}
     */
    @Override
    public void clearCache(Class<?> mapper) {
        log.info("Clear mybatis cache [{}].", mapper);
        final Cache cache = getCache(mapper);
        if (cache != null) {
            cache.clear(); 
        }
        else {
            log.warn("No mybatis cache [{}] found.", mapper);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Cache getCache(Class<?> mapper) {
        return configuration.getCache(mapper.getName());
    }

    // --
    // private methods

    @PostConstruct
    void init() {
         configuration = ssf.getConfiguration();
    }
}
