package com.chenyang.nse.bussiness.odbc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.chenyang.nse.bussiness.odbc.business.OdbcApi;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.StandardCharsets;

public class ApiHandler extends ChannelInboundHandlerAdapter {
   public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      ByteBuf byteBuf = (ByteBuf)msg;
      byte[] buffer = new byte[byteBuf.readableBytes()];
      byteBuf.readBytes(buffer);
      Object response = OdbcApi.service(buffer);
      String json = "{}";
      if (response != null) {
         if (response instanceof String) {
            json = (String)response;
         } else {
            ObjectMapper mapper = new ObjectMapper();
            json = mapper.writeValueAsString(response);
         }
      }

      json = json + "\n\n";
      byte[] jsonBuf = json.getBytes(StandardCharsets.UTF_8);
      ByteBuf buf = Unpooled.wrappedBuffer(jsonBuf);
      ctx.writeAndFlush(buf);
      buf.clear();
   }
}
