package org.vertexium.accumulo;

import org.apache.accumulo.core.data.ByteSequence;
import org.cache2k.Cache;
import org.cache2k.Cache2kBuilder;
import org.vertexium.accumulo.iterator.util.ByteSequenceUtils;
import org.vertexium.id.IdentityNameSubstitutionStrategy;
import org.vertexium.id.NameSubstitutionStrategy;

import java.util.Map;

public class AccumuloNameSubstitutionStrategy implements NameSubstitutionStrategy {
    private final NameSubstitutionStrategy nameSubstitutionStrategy;
    private final Cache<ByteSequence, String> inflateTextCache;

    protected AccumuloNameSubstitutionStrategy(NameSubstitutionStrategy nameSubstitutionStrategy) {
        this.nameSubstitutionStrategy = nameSubstitutionStrategy;
        inflateTextCache = Cache2kBuilder.of(ByteSequence.class, String.class)
            .name(AccumuloNameSubstitutionStrategy.class, "inflateTextCache-" + System.identityHashCode(this))
            .entryCapacity(10000)
            .eternal(true)
            .loader(byteSequence -> inflate(ByteSequenceUtils.toString(byteSequence)))
            .build();
    }

    @Override
    public void setup(Map config) {
        return;
    }

    @Override
    public String deflate(String value) {
        return this.nameSubstitutionStrategy.deflate(value);
    }

    @Override
    public String inflate(String value) {
        return this.nameSubstitutionStrategy.inflate(value);
    }

    public String inflate(ByteSequence text) {
        if (text == null) {
            return null;
        }
        if (this.nameSubstitutionStrategy instanceof IdentityNameSubstitutionStrategy) {
            return text.toString();
        }
        return inflateTextCache.get(text);
    }

    public static AccumuloNameSubstitutionStrategy create(NameSubstitutionStrategy nameSubstitutionStrategy) {
        if (nameSubstitutionStrategy instanceof AccumuloNameSubstitutionStrategy) {
            return (AccumuloNameSubstitutionStrategy) nameSubstitutionStrategy;
        }
        return new AccumuloNameSubstitutionStrategy(nameSubstitutionStrategy);
    }
}

@@ -81,69 +81,8 @@
 ce;%0A
-import org.cache2k.Cache;%0Aimport org.cache2k.Cache2kBuilder;%0A
 impo
@@ -140,16 +140,16 @@
 eUtils;%0A
+
 import o
@@ -428,72 +428,8 @@
 egy;
-%0A    private final Cache%3CByteSequence, String%3E inflateTextCache;
 %0A%0A  
@@ -596,368 +596,8 @@
 gy;%0A
-        inflateTextCache = Cache2kBuilder.of(ByteSequence.class, String.class)%0A            .name(AccumuloNameSubstitutionStrategy.class, %22inflateTextCache-%22 + System.identityHashCode(this))%0A            .entryCapacity(10000)%0A            .eternal(true)%0A            .loader(byteSequence -%3E inflate(ByteSequenceUtils.toString(byteSequence)))%0A            .build();%0A
     
@@ -653,24 +653,8 @@
 ) %7B%0A
-        return;%0A
     
@@ -1175,27 +1175,42 @@
 late
-TextCache.get
+(ByteSequenceUtils.toString
 (text)
+)
 ;%0A  

remove rarely used cache