package com.jpsoft.uniview.handler;

import cn.hutool.json.JSONObject;
import com.jpsoft.uniview.dto.HeartReportInfo;
import com.jpsoft.uniview.dto.LapiResponse;
import com.jpsoft.uniview.dto.PersonVerification;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ParseHttpHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest){
            FullHttpRequest request = (FullHttpRequest)msg;

            ByteBuf byteBuf = request.content();

            byteBuf.markReaderIndex();

            byte[] buffer = new byte[byteBuf.readableBytes()];

            for(int i=0;i<buffer.length;i++) {
                buffer[i] = byteBuf.readByte();
            }

            byteBuf.resetReaderIndex();

            log.warn(request.uri());

            String json = new String(buffer,"UTF-8");

            if(request.uri().contains("HeartReportInfo")) {
                JSONObject jsonObject = new JSONObject(json);
                HeartReportInfo heartReportInfo = jsonObject.toBean(HeartReportInfo.class);

                ctx.fireChannelRead(heartReportInfo);
            }
            else if(request.uri().contains("Notifications")
                 || request.uri().contains("PersonVerification")) {
                PersonVerification personVerification = new PersonVerification();
                personVerification.setUri(request.uri());

                JSONObject jsonObject = new JSONObject(json);
                personVerification.setJsonObject(jsonObject);

                ctx.fireChannelRead(personVerification);
            }
        }
        else if(msg instanceof FullHttpResponse){
            FullHttpResponse response = (FullHttpResponse)msg;

            ByteBuf byteBuf = response.content();

            byteBuf.markReaderIndex();

            byte[] buffer = new byte[byteBuf.readableBytes()];

            for(int i=0;i<buffer.length;i++) {
                buffer[i] = byteBuf.readByte();
            }

            byteBuf.resetReaderIndex();

            String json = new String(buffer,"UTF-8");

            JSONObject jsonObject = new JSONObject(json);

            LapiResponse lapiResponse = new LapiResponse();
            lapiResponse.setData(jsonObject);

            ctx.fireChannelRead(lapiResponse);
        }
    }
}