package com.yx.face.netty_server;

import com.alibaba.fastjson.JSONObject;
import com.yx.face.service.PushService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @ProjectName: face-server-netty
 * @Package: com.yx.face.nettyclient
 * @ClassName: RequestServerHandler
 * @Author: 崔哥
 * @Description: 自定义业务处理handler
 * @Date: 2021/11/22 13:26
 * @Version: 1.0
 */
@Slf4j
public class RequestServerHandler extends ChannelInboundHandlerAdapter {

    private PushService PushService;

    public RequestServerHandler(PushService PushService) {
        this.PushService = PushService;
    }

    /**
     * 服务端连接到客户端戳发该函数调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端连接到客户度:" + ctx.channel().remoteAddress());
    }

    /**
     * 接收服务端的数据 并处理完
     *
     * @param ctx
     * @param obj
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        System.out.println("-----" + obj);
        if (null != obj) {
            log.info("server received::" + obj.toString());
            String receivedMsg = obj.toString();
            try {
                //业务代码
                String faceLog = JSONObject.parseObject(receivedMsg).getString("face-log");
                if (StringUtils.isNotBlank(faceLog)) {
                    String deviceSn = JSONObject.parseObject(faceLog).getString("deviceSn");
                    if (StringUtils.isNotBlank(deviceSn)) {
                        PushService.push(deviceSn, faceLog);
                    }
                }
                String userVisitor = JSONObject.parseObject(receivedMsg).getString("user-visitor");
                if (StringUtils.isNotBlank(userVisitor)) {
                    PushService.pushVisitor(userVisitor);
                }
            } catch (Exception exception) {
                //异常处理代码
                log.error("system_error::" + "sendDataHeader" + "5001|" + exception.getMessage());
            } finally {
                ctx.channel().close();
                ctx.flush();
            }
        }
    }

    /**
     * 发生异常 打印信息 关闭所有链路
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

}
