package click.kamil.springstatemachineexporter.analysis.index;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public final class GetterChainIndex {

    private static final GetterChainIndex EMPTY = new GetterChainIndex(Map.of(), 0);

    private final Map<String, Map<String, GetterChainEdge>> byOwnerAndGetter;
    private final int edgeCount;

    public GetterChainIndex(Map<String, Map<String, GetterChainEdge>> byOwnerAndGetter, int edgeCount) {
        this.byOwnerAndGetter = Collections.unmodifiableMap(deepCopy(byOwnerAndGetter));
        this.edgeCount = edgeCount;
    }

    public static GetterChainIndex empty() {
        return EMPTY;
    }

    public Optional<GetterChainEdge> lookup(String ownerFqn, String getterName) {
        if (ownerFqn == null || getterName == null) {
            return Optional.empty();
        }
        Map<String, GetterChainEdge> getters = byOwnerAndGetter.get(ownerFqn);
        if (getters == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(getters.get(getterName));
    }

    public int edgeCount() {
        return edgeCount;
    }

    private static Map<String, Map<String, GetterChainEdge>> deepCopy(
            Map<String, Map<String, GetterChainEdge>> source) {
        Map<String, Map<String, GetterChainEdge>> copy = new HashMap<>();
        for (Map.Entry<String, Map<String, GetterChainEdge>> entry : source.entrySet()) {
            copy.put(entry.getKey(), Map.copyOf(entry.getValue()));
        }
        return copy;
    }
}
