package org.hanuna.gitalk.common;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

/**
 * @author erokhins
 */
public class CacheGet<K, V> implements Get<K, V>{
    private final Get<K, V> getFunction;
    private final int size;
    private Map<K, V> map;
    private Map<K, V> moreMap;

    public CacheGet(@NotNull Get<K, V> getFunction, int size) {
        this.getFunction = getFunction;
        this.size = size;
        this.map = new HashMap<K, V>(2 * size);
        this.moreMap = new HashMap<K, V>(2 * size);
    }

    public CacheGet(@NotNull Get<K, V> getFunction) {
        this(getFunction, 100);
    }

    public void clear() {
        this.map.clear();
        this.moreMap.clear();
    }

    @NotNull
    @Override
    public V get(@NotNull K key) {
        V value = moreMap.get(key);
        if (value != null) {
            return value;
        } else {
            value = getFunction.get(key);
            moreMap.put(key, value);
            map.put(key, value);
            checkSize();
            return value;
        }
    }

    private void checkSize() {
        if (map.size() >= size) {
            Map<K, V> tempMap = moreMap;
            moreMap = map;
            map = tempMap;
            map.clear();
        }
    }
}

@@ -196,16 +196,17 @@
 et%3CK, V%3E
+ 
 %7B%0A    pr
@@ -974,19 +974,18 @@
     
-moreMap.put
+addToCache
 (key
@@ -1010,27 +1010,20 @@
     
-map.put(key,
+return
  value
-)
 ;%0A  
@@ -1032,49 +1032,140 @@
     
+%7D%0A
     
-checkSize();%0A            return
+%7D%0A%0A    public void addToCache(@NotNull K key, @NotNull V value) %7B%0A        moreMap.put(key, value);%0A        map.put(key,
  value
+)
 ;%0A  
@@ -1162,33 +1162,44 @@
 value);%0A        
-%7D
+checkSize();
 %0A    %7D%0A%0A    priv

add CacheGet.addToCache(key, value)