package top.leisuretimedock.dglabgame.core.manager;

import com.r3944realms.dg_lab.api.websocket.message.role.WebSocketClientRole;
import com.r3944realms.dg_lab.manager.DGPBClientManager;
import com.r3944realms.dg_lab.websocket.PowerBoxWSClient;
import com.r3944realms.dg_lab.websocket.handler.client.DefaultClientOperation;
import com.r3944realms.dg_lab.websocket.sharedData.ClientPowerBoxSharedData;
import top.leisuretimedock.dglabgame.config.CommonConfig;

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

public class ClientManager implements IManager<Map<String, DGPBClientManager>> {
    private final Map<String, DGPBClientManager> clients = new HashMap<>();

    public DGPBClientManager createClient(String key, WebSocketClientRole role) {
        return createClient(key, role, CommonConfig.ADDRESS.get(), CommonConfig.PORT.get());
    }

    public DGPBClientManager createClient(String key, WebSocketClientRole role, String address, int port) {
        ClientPowerBoxSharedData sharedData = new ClientPowerBoxSharedData(
                CommonConfig.ANTI_SHAKE_DELAY.get()
        );
        sharedData.address = address;
        sharedData.port = port;

        PowerBoxWSClient wsClient = new PowerBoxWSClient(
                sharedData, role, new DefaultClientOperation(),
                address, port
        );
        DGPBClientManager client = new DGPBClientManager(wsClient);
        clients.putIfAbsent(key, client);
        return client;
    }

    public java.util.Set<String> getClientNames() {
        return clients.keySet();
    }

    public void addClient(String key, DGPBClientManager client) {
        clients.putIfAbsent(key, client);
    }

    public void removeClient(String key) {
        Optional.ofNullable(clients.remove(key)).ifPresent(DGPBClientManager::stop);
    }

    public Optional<DGPBClientManager> getClient(String key) {
        return Optional.ofNullable(clients.get(key));
    }

    @Override
    public void startAll() {
        clients.values().forEach(DGPBClientManager::start);
    }

    @Override
    public void stopAll() {
        clients.values().forEach(DGPBClientManager::stop);
    }

    @Override
    public Optional<Map<String, DGPBClientManager>> getInstance() {
        return Optional.of(clients);
    }
}
