package com.palacesun.engine.gateway.netty.framework;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;

public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
   public void channelReadComplete(ChannelHandlerContext ctx) {
      ctx.flush();
   }

   protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
      if (HttpUtil.is100ContinueExpected(req)) {
         ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
      }

      try {
         GatewayRequestHandler.switchHanderMethod(req);
      } catch (Exception e) {
         e.printStackTrace();
      }

      String data = "接口推送完成！";
      ByteBuf buf = this.copiedBuffer(data, CharsetUtil.UTF_8);
      FullHttpResponse response = null;
      response = this.responseOk(HttpResponseStatus.OK, buf);
      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
   }

   public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
      ctx.writeAndFlush("GATEWAY_PUSH_OK!").addListener(ChannelFutureListener.CLOSE);
   }

   private FullHttpResponse responseOk(HttpResponseStatus status, ByteBuf buf) {
      FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buf);
      if (buf != null) {
         response.headers().set("Content-Type", "text/plain;charset=UTF-8");
         response.headers().set("Content-Length", response.content().readableBytes());
      }

      return response;
   }

   private ByteBuf copiedBuffer(String data, Charset utf8) {
      return Unpooled.wrappedBuffer(data.getBytes());
   }
}
