package ink.wgink.module.file.impl;

import ink.wgink.exceptions.ParamsException;
import ink.wgink.interfaces.manager.IFilesShowCodeService;
import ink.wgink.pojo.bos.files.FilesShowCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: FileShowCodeServiceImpl
 * @Description: 文件显示码
 * @Author: wanggeng
 * @Date: 2022/8/1 17:16
 * @Version: 1.0
 */
@Service
public class DefaultFilesShowCodeServiceImpl implements IFilesShowCodeService {
    private static final Logger LOG = LoggerFactory.getLogger(DefaultFilesShowCodeServiceImpl.class);
    private Map<String, FilesShowCode> showCodeMap = new ConcurrentHashMap<>();

    @Override
    public void addShowCode(String code, String fileId, String fileName) {
        showCodeMap.put(fileId, new FilesShowCode(code, fileId, fileName));
    }

    @Override
    public void clearTimeoutShowCode() {
        Set<String> keySet = showCodeMap.keySet();
        long currentTimeMillis = System.currentTimeMillis();
        long clearTimeoutShowCodeCount = 0;
        for (String key : keySet) {
            FilesShowCode showCode = getShowCode(key);
            if (currentTimeMillis - showCode.getLatestUpdateTime() > SHOW_CODE_TIMEOUT_MILLIS) {
                showCodeMap.remove(key);
                clearTimeoutShowCodeCount++;
            }
        }
        LOG.trace(">>>>>> count of clear timeout show code: {}", clearTimeoutShowCodeCount);
    }

    @Override
    public FilesShowCode getShowCode(String fileId, String code) {
        FilesShowCode showCode = getShowCode(fileId);
        if (showCode == null) {
            throw new ParamsException("查看码不存在");
        }
        if (!StringUtils.equals(showCode.getCode(), code)) {
            throw new ParamsException("查看码不匹配");
        }
        return showCode;
    }

    @Override
    public synchronized FilesShowCode getShowCode(String fileId) {
        FilesShowCode showCode = showCodeMap.get(fileId);
        if (showCode != null) {
            showCode.setLatestUpdateTime(System.currentTimeMillis());
        }
        return showCode;
    }


}
