package com.keyware.shandan.bianmu.export;

import com.keyware.shandan.common.util.StringUtils;

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

public class ExportCache {
    private final static ConcurrentHashMap<String, Map<String, ExportProgress>> cache = new ConcurrentHashMap<>();

    public static void startExport(ExportProgress progress) {
        Map<String, ExportProgress> userCache = cache.get(progress.getUserId());
        if (userCache == null) {
            userCache = new HashMap<>();
        }
        userCache.put(progress.getExportId(), progress);
        cache.put(progress.getUserId(), userCache);
        new Thread(progress).start();
    }

    public static <T extends ExportProgress> T getCache(String userId, String exportId) {
        Map<String, ExportProgress> userCache = cache.get(userId);
        if (userCache == null) {
            return null;
        }
        if (StringUtils.hasText(exportId)) {
            return (T) userCache.get(exportId);
        }
        Optional<ExportProgress> optional = userCache.values().stream().findFirst();
        if (optional.isPresent()) {
            return (T) optional.get();
        }
        return null;
    }

    public static <T extends ExportProgress> T popCache(String userId, String exportId) {
        Map<String, ExportProgress> userCache = cache.get(userId);
        if (userCache == null) {
            return null;
        } else {
            ExportProgress progress = userCache.remove(exportId);
            return (T) progress;
        }
    }
}
