package org.ts.ddcs.net;

import org.ts.ddcs.main.DataProcessHolder;
import org.ts.ddcs.dataStream.DataStreamAdapter;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.constant.NetPortStatus;


import javax.swing.plaf.PanelUI;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

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

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

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

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

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

    public void addUdpChannel(String agreement, int port) {
        String key = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        DataChannelUdpWithNio instance = new DataChannelUdpWithNio(key, agreement);
        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) {

        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!onlineChannelByKey.containsKey(dataStreamAdapter.getAdapterKey())) {
            onlineChannelByKey.put(dataStreamAdapter.getAdapterKey(), dataStreamAdapter);
        }
//            String rtuCode = dataStreamAdapter.getCode();
//            if (null != rtuCode && rtuCode.length() > 0) {
//                HashOperations<String, String, String> ops = DataProcessHolder.newInstance().dataProcess.redisTemplate.opsForHash();
//                ops.put(rtuCode, "last_connect_id", dataStreamAdapter.getAdapterKey());
//                ops.put(rtuCode, "last_connect_time", sdf.format(dataStreamAdapter.getCreateTime()));
//            }
        //    return true;

    }

    public void offline(DataStreamAdapter dataStreamAdapter) {
        // try {
        //  if (onlineChannelByKey.containsKey(dataStreamAdapter.getAdapterKey())) {
        onlineChannelByKey.remove(dataStreamAdapter.getAdapterKey());

        //   }
//        } catch (Exception e) {
//            LogHelper.error(e);
//        }
    }
}
