package top.baogutang.strategy.models;

import top.baogutang.strategy.commons.enums.Timeframe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class MarketDataCache {
    private final Map<Timeframe, NavigableMap<Long, Kline>> map = new ConcurrentHashMap<>();
    private final int maxBars;

    public MarketDataCache(int maxBars) {
        this.maxBars = maxBars;
    }

    public void upsert(Timeframe tf, Kline k) {
        if (!map.containsKey(tf)) {
            map.put(tf, new ConcurrentSkipListMap<Long, Kline>());
        }
        NavigableMap<Long, Kline> m = map.get(tf);
        m.put(k.openTime(), k);
        while (m.size() > maxBars) {
            Map.Entry<Long, Kline> e = m.pollFirstEntry();
            if (e == null) break;
        }
    }

    public List<Kline> lastN(Timeframe tf, int n) {
        NavigableMap<Long, Kline> m = map.get(tf);
        if (m == null || m.isEmpty()) return Collections.emptyList();
        List<Kline> tmp = new ArrayList<Kline>(m.values());
        int size = tmp.size();
        if (n >= size) return tmp;
        return tmp.subList(size - n, size);
    }

    public Kline last(Timeframe tf) {
        NavigableMap<Long, Kline> m = map.get(tf);
        if (m == null || m.isEmpty()) return null;
        return m.lastEntry().getValue();
    }
}
