package com.ruoyi.file.utils;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.file.domain.Project;
import com.ruoyi.file.mapper.ProjectMapper;

import java.util.Collection;
import java.util.List;

public final class ProjectUtils
{
    private static final String PROJECT_CACHE_PREFIX = "project:";

    private static String ProjectCacheKey(String what)
    {
        return PROJECT_CACHE_PREFIX + what;
    }

    private static RedisCache RedisCache()
    {
        return SpringUtils.getBean(RedisCache.class);
    }

    private static void SetupCache(ProjectMapper projectMapper)
    {
        Project cond = new Project();
        cond.setDisabled("0");
        List<Project> projects = projectMapper.selectProjectList(cond);
        if(projects.isEmpty())
            return;
        RedisCache redisCache = RedisCache();
        projects.forEach((x) -> {
            redisCache.setCacheObject(ProjectCacheKey(x.getToken()), x);
        });
    }

    public static void CleanCache()
    {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(ProjectCacheKey("*"));
        RedisCache().deleteObject(keys);
    }

    public static void ReloadCache(ProjectMapper projectMapper)
    {
        CleanCache();
        SetupCache(projectMapper);
    }

    public static Project Get(String token)
    {
        return RedisCache().getCacheObject(ProjectCacheKey(token));
    }

    public static void Set(Project project)
    {
        RedisCache().setCacheObject(ProjectCacheKey(project.getToken()), project);
    }

    public static void Del(String token)
    {
        RedisCache().deleteObject(ProjectCacheKey(token));
    }

    private ProjectUtils() {}
}
