package com.docus.server.common.netty.server;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * 客户端IP和通信信道的映射
 */
@Component
@Slf4j
public class ChannelRepository {


    private final static Map<String, Channel> CHANNEL_CACHE_MAP = new ConcurrentHashMap<>();

    /**
     * 客户端上线
     *
     * @param key
     * @param value
     */
    public void put(String key, Channel value) {
        //客户端上线
        CHANNEL_CACHE_MAP.put(key, value);
        AttributeKey<String> attributeKey = AttributeKey.valueOf("user");
        value.attr(attributeKey).set(key);
        //todo 数据库更新工控机状态上线
    }

    public String getClientKey(Channel channel) {
        AttributeKey<String> key = AttributeKey.valueOf("user");
        if (channel.hasAttr(key)) {
            return channel.attr(key).get();
        }
        return null;
    }

    public Channel get(String key) {
        return CHANNEL_CACHE_MAP.get(key);
    }

    /**
     * 工控机离线,工控机上所有设备离线
     *
     * @param key
     */
    public void remove(String key) {
        CHANNEL_CACHE_MAP.remove(key);
        //todo 数据库更新工控机状态离线
    }

}
