package org.ts.ddcs.net;

import org.ts.ddcs.dataStream.DataStreamAdapter;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 网络模块
 *
 * @author swp
 */
public class DataChannel {

    private ConcurrentHashMap<String, DataStreamAdapter> onlineChannelByKey = new ConcurrentHashMap<>();

    private Map<String, DataChannelTcpWithNio> dataChannelWithNioMap = new HashMap<>();

    private Map<String, DataChannelUdpWithNio> datagramWithNioMap = new HashMap<>();

    public void addTcpChannel(int port) {
        String key = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        DataChannelTcpWithNio instance = new DataChannelTcpWithNio(key);
        instance.colseChannel().openChannel(port).async();
        this.dataChannelWithNioMap.put(key, instance);
    }

    public void addTcpChannel(String agreement, int port) {
        String key = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        DataChannelTcpWithNio instance = new DataChannelTcpWithNio(key, agreement.toUpperCase());
        instance.colseChannel().openChannel(port).async();
        this.dataChannelWithNioMap.put(key, instance);
    }

    public void addUdpChannel(int port) {
        String key = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        DataChannelUdpWithNio instance = new DataChannelUdpWithNio(key);
        instance.colseChannel().openChannel(port).async();
        this.datagramWithNioMap.put(key, instance);
    }

    public void addUdpChannel(String agreement, int port) {
        String key = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        DataChannelUdpWithNio instance = new DataChannelUdpWithNio(key, agreement.toUpperCase());
        instance.colseChannel().openChannel(port).async();
        this.datagramWithNioMap.put(key, instance);
    }

    public DataStreamAdapter getDataTemplateAdapterByKey(String key) {
        if (onlineChannelByKey.containsKey(key)) {
            return onlineChannelByKey.get(key);
        }
        return null;
    }

    public void online(DataStreamAdapter dataStreamAdapter) {
        onlineChannelByKey.put(dataStreamAdapter.getAdapterKey(), dataStreamAdapter);
    }

    public void offline(DataStreamAdapter dataStreamAdapter) {
        onlineChannelByKey.remove(dataStreamAdapter.getAdapterKey());
    }
}
