package com.its.pis.xnettcp;

import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class TcpServerManager {

    private ChannelGroup channelGroup;
    private static ConcurrentHashMap<String, Object> CONNECTION_LIST = new ConcurrentHashMap();

    @PostConstruct
    public void init() {
        log.info("TcpServerManager-init");
        this.channelGroup = (ChannelGroup)new DefaultChannelGroup((EventExecutor) GlobalEventExecutor.INSTANCE);
    }

    public ChannelGroup getChannelGroup() {
        return this.channelGroup;
    }

    public void addChannel(String ipAddress, Object obj) {
        this.CONNECTION_LIST.put(ipAddress, obj);
        log.info("TcpServerManager-Add Channel: {}, {} Connections.", ipAddress, this.CONNECTION_LIST.size());
    }

    public void delChannel(String ipAddress) {
        this.CONNECTION_LIST.remove(ipAddress);
        log.info("TcpServerManager-Del Channel: {}, {} Connections.", ipAddress, this.CONNECTION_LIST.size());
    }

    public ConcurrentHashMap<String, Object> getConnectionList() {
        return this.CONNECTION_LIST;
    }
}
