package click.kamil.springstatemachineexporter.analysis.index;

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

public final class FieldTypeIndex {

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

    private final Map<String, Map<String, String>> byOwnerAndField;
    private final int fieldCount;

    public FieldTypeIndex(Map<String, Map<String, String>> byOwnerAndField, int fieldCount) {
        this.byOwnerAndField = Collections.unmodifiableMap(deepCopy(byOwnerAndField));
        this.fieldCount = fieldCount;
    }

    public static FieldTypeIndex empty() {
        return EMPTY;
    }

    public Optional<String> lookup(String ownerFqn, String fieldName) {
        if (ownerFqn == null || fieldName == null) {
            return Optional.empty();
        }
        Map<String, String> fields = byOwnerAndField.get(ownerFqn);
        if (fields == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(fields.get(fieldName));
    }

    public int fieldCount() {
        return fieldCount;
    }

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