package ru.dragonestia.kubik.discovery.component;


import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import ru.dragonestia.kubik.discovery.model.ServerIdentifierStrategy;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Log4j2
@Component
public class ServerIdentifierGenerator implements ServerIdentifierStrategy {

    private final Map<Key, String> rememberedServers = new ConcurrentHashMap<>();
    private final Map<String, AtomicInteger> groupFreeIds = new ConcurrentHashMap<>();

    @Override
    public synchronized String of(String groupId, String address, int port) {
        var key = new Key(groupId, address, port);
        return rememberedServers.computeIfAbsent(key, _ -> {
            var id = groupFreeIds.computeIfAbsent(groupId, _ -> new AtomicInteger(0));
            return "%s_%s".formatted(groupId, id.getAndIncrement());
        });
    }

    private record Key(String groupId, String address, int port) {}
}
