package thyyxxk.webserver.service.hutoolcache;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.dao.his.hutoolcache.HutoolCacheDao;

import java.util.List;

@Service
public class OccupationCache implements HutoolCacheInterface<OccupationCache.Occupation> {
    private final HutoolCacheDao dao;
    private static final int CACHE_SIZE = 32;
    Cache<String, Occupation> cache = CacheUtil.newLFUCache(CACHE_SIZE);

    @Data
    public static class Occupation {
        private String code;
        private String name;
        private String pyCode;
    }

    @Autowired
    public OccupationCache(HutoolCacheDao dao) {
        this.dao = dao;
    }

    @Override
    public void put(String key, Occupation value) {
        if (value != null) {
            cache.put(key, value);
        }
    }

    @Override
    public Occupation get(String key) {
        if (StrUtil.isBlank(key)) {
            return new Occupation();
        }
        Occupation occupation = cache.get(key);
        if (occupation == null) {
            occupation = dbInfo(key);
            put(key, occupation);
        }
        return occupation;
    }

    @Override
    public void del(String key) {
        cache.remove(key);
    }

    @Override
    public void clear() {
        cache.clear();
    }

    public Occupation dbInfo(String key) {
        return dao.selectOccupation(key);
    }

    public String getOccupationName(String code) {
        Occupation occupation = get(code);
        if (occupation != null) {
            return occupation.getName();
        }
        return null;
    }

    @Override
    public List<CacheAll> getAll() {
        return this.getAllUtils(cache.cacheObjIterator());
    }

    @Override
    public void refreshCache(String key) {
        put(key, dbInfo(key));
    }

    @Override
    public String getLabel() {
        return "国家";
    }
}
