package com.zd.netty.handler;

import com.zd.common.core.utils.SpringUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.redis.service.RedisService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Socket拦截器，用于处理客户端的行为
 *
 * @author dgs
 **/
public class SocketHandler extends ChannelInboundHandlerAdapter {
    protected static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final Logger log = LoggerFactory.getLogger(SocketHandler.class);

    private static ConcurrentHashMap<String, ChannelHandlerContext> map = new ConcurrentHashMap<>();

    private static final String RFID_CODE="RFID:";

    /**
     * 读取到客户端发来的消息
     *
     * @param ctx ChannelHandlerContext
     * @param msg msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        byte[] data = (byte[]) msg;
        String str=byte2Hex(data);
        if(StringUtils.isEmpty(str)){
             return;
        }
        String upperCase=str.toUpperCase();
        log.info("转换后消息:{}",upperCase);
        upperCase=upperCase.substring(8,32);
        log.info("截取后:{}",upperCase);
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        String t= redisService.getCacheObject(RFID_CODE+upperCase);
        if(StringUtils.isNotNull(t)){
            return;
        }
        redisService.setCacheObject(RFID_CODE+upperCase,upperCase,5L, TimeUnit.MINUTES);
        log.info("需要存入数据");
        synchronized (this){
            // 根据实际业务应用实现下方接口,进行业务操作，可根据type多方实现，多方发送接收到的编码
            // TODO document why this method is empty

//            ISendService sendService = SpringUtils.getBean(ISendService.class);
//            sendService.send(upperCase,0);
        }
    }

    /**
     　　 * 将byte转为16进制
     　　 * @param bytes
     　　 * @return
     　　 */
    public static String byte2Hex(byte[] bytes){
        StringBuilder builder = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        String s = channel.id().asShortText();
        log.info("新的客户端链接：{}" , s);
        clients.add(channel);
        String uuid = ctx.channel().id().asLongText();
        map.put(uuid, ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        clients.remove(ctx.channel());
        String uuid = ctx.channel().id().asLongText();
        map.remove(uuid);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        cause.printStackTrace();
        ctx.channel().close();
        clients.remove(ctx.channel());
    }
}
