package www.liujijiji.cn.netty.udp;

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 io.netty.util.internal.ThreadLocalRandom;


/**
 * @author liuji
 * @date 2018 - 09 - 07 22:02
 */
public class ServerHandler extends SimpleChannelInboundHandler<DatagramPacket>{


    private static final String[] DICTIONARY = {
        "踮起脚，她的指尖",
        "就要触摸到自认为的果子，",
        "其实那只是花蕾，青涩的蕾壳包裹如小房间。",
        "她天真烂漫，只会叫嚷：“果子，果子啊。”",
        "那没什么不好，当世界落寞如枝头的山茶花，",
        "在寒冷之中如我与之都需要一些阳光取暖，",
        "那夜里的梦霾都被她摇摆的小手驱散了。",
        "这并没什么不好的。",
        "是的，我们都需要香甜的果子，",
        "和玩耍的方法，包括人造园林"
    };

    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket data) throws Exception {

        String req = data.content().toString(CharsetUtil.UTF_8);
        System.out.println(req);


        if ("查询请求".equals(req)){
            ctx.writeAndFlush(
                    new DatagramPacket(
                            Unpooled.copiedBuffer("查询结果: " +nextQuote(),
                            CharsetUtil.UTF_8),
                            data.sender()
                    )
            );
        }

    }

    private String nextQuote() {
        int quoteId = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
        return DICTIONARY[quoteId];
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }


}
