package com.qmth.exam.reserve.cache.impl;

import com.qmth.exam.reserve.bean.examsite.ExamSiteCacheBean;
import com.qmth.exam.reserve.cache.CacheConstants;
import com.qmth.exam.reserve.cache.RedisClient;
import com.qmth.exam.reserve.dao.ExamSiteDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class ExamSiteCacheService implements CacheConstants {

    private static final Logger log = LoggerFactory.getLogger(ExamSiteCacheService.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private ExamSiteDao examSiteDao;

    /**
     * 获取某个考点缓存
     */
    public ExamSiteCacheBean getExamSiteById(Long examSiteId) {
        String cacheKey = String.format(CACHE_EXAM_SITE, examSiteId);
        ExamSiteCacheBean value = redisClient.get(cacheKey, ExamSiteCacheBean.class);
        if (value != null) {
            return value;
        }

        value = examSiteDao.findInfoById(examSiteId);
        if (value == null) {
            return null;
        }

        redisClient.set(cacheKey, value, 10, TimeUnit.MINUTES);
        log.info("SET cacheKey:{}", cacheKey);

        return value;
    }

    public void clearExamSiteByIdCache(Long examSiteId) {
        String cacheKey = String.format(CACHE_EXAM_SITE, examSiteId);
        redisClient.delete(cacheKey);
        log.warn("DELETE cacheKey:{}", cacheKey);
    }

}
