package org.bdware.sc.units;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class RequestCache {
    public static final int RESERVED = 10;   //只保留每个合约的仅10条请求缓存
    //    private static final Logger LOGGER = LogManager.getLogger(RequestCache.class);
    private final long time;
    private final Map<Integer, String> requests = new TreeMap<>(); //key is seq

    public RequestCache() {
        time = System.currentTimeMillis();
    }

    public synchronized void put(Integer seq, String arg) {
        requests.put(seq, arg);
    }

    public synchronized String get(Integer seq) {
        return requests.get(seq);
    }

    public synchronized int size() {
        return requests.size();
    }

    public synchronized boolean containsKey(Integer id) {
        return requests.get(id) != null;
    }

    public synchronized long getTime() {
        return time;
    }

    //只保留最近RESERVED条请求
    public synchronized void decSize() {
        int size = requests.size();
        if (size <= RESERVED)
            return;

        int count = 0, total = size - RESERVED;
        List<Integer> indexs = new ArrayList<>(total);
        for (Integer i : requests.keySet()) {
            if (count == total)
                break;
            indexs.add(i);
            count++;
        }
        for (int i = 0; i < total; i++) {
            requests.remove(indexs.get(i));
        }
    }
}
