package ink.wgink.module.file.manager;

import ink.wgink.module.file.dao.fileclient.IFileClientDao;
import ink.wgink.module.file.pojo.dtos.fileclient.FileClientDTO;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: FileRemoteManager
 * @Description: 文件远程管理
 * @Author: wanggeng
 * @Date: 2022/8/4 23:16
 * @Version: 1.0
 */
public class FileRemoteManager {

    private static FileRemoteManager fileRemoteManager = FileRemoteManagerBuilder.fileRemoteManager;
    private Map<String, String> updateKeyValueMap = new ConcurrentHashMap<>();
    private IFileClientDao fileRemoteDao;

    private FileRemoteManager() {

    }

    public static FileRemoteManager getInstance() {
        return fileRemoteManager;
    }

    public void refresh() {
        updateKeyValueMap.clear();
        Map<String, Object> params = new HashMap<>();
        params.put("status", "active");
        List<FileClientDTO> fileClientDTOS = fileRemoteDao.list(params);
        for (FileClientDTO fileClientDTO : fileClientDTOS) {
            updateKeyValueMap.put(fileClientDTO.getAccessKey(), fileClientDTO.getAccessSecret());
        }
    }

    /**
     * 校验
     *
     * @param updateKey
     * @param updateSecret
     * @return
     */
    public boolean check(String updateKey, String updateSecret) {
        if (StringUtils.isBlank(updateKey) || StringUtils.isBlank(updateSecret)) {
            return false;
        }
        String existUpdateSecret = updateKeyValueMap.get(updateKey);
        if (!StringUtils.equals(updateSecret, existUpdateSecret)) {
            return false;
        }
        return true;
    }

    public void setFileRemoteDao(IFileClientDao fileRemoteDao) {
        this.fileRemoteDao = fileRemoteDao;
        refresh();
    }

    private static class FileRemoteManagerBuilder {
        public static FileRemoteManager fileRemoteManager = new FileRemoteManager();
    }

}
