package com.mortals.xhx.daemon.netty.server.controlserver.handler;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.device.service.DeviceService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

import static com.mortals.xhx.common.key.Constant.PARAM_SERVER_HTTP_URL;


/**
 * 业务处理
 *
 * @author: zxfei
 * @date: 2022/4/8 10:20
 */
@Slf4j
public class NettyUDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private DeviceService deviceService;

    public NettyUDPServerHandler(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {

        ByteBuf byteBuf = packet.copy().content();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String content = new String(bytes);
        log.info("receive->UDP:{}", packet.sender().toString() + "," + content);

        // TODO 设备返回服务端配置
        String URL = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://192.168.0.98:11021");
        // String req = msg.content().toString(CharsetUtil.UTF_8);
        ApiResp<String> resp = new ApiResp<>();
        resp.setCode(YesNoEnum.YES.getValue());
        resp.setMsg("获取服务端地址成功！");
        resp.setData(URL);


        //InetSocketAddress remoteAddress = new InetSocketAddress("255.255.255.255", 7789);
        InetSocketAddress remoteAddress = new InetSocketAddress( packet.sender().getHostName(), 7789);
        DatagramPacket sendpacket =new DatagramPacket(Unpooled.copiedBuffer(JSON.toJSONString(resp), CharsetUtil.UTF_8),remoteAddress);

        //ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(JSON.toJSONString(resp), CharsetUtil.UTF_8), packet.sender()));
        ctx.writeAndFlush(sendpacket);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // TODO Auto-generated method stub
        ctx.close();
        cause.printStackTrace();
    }
}
