package io.github.hapjava.server.impl.http.impl;

import io.github.hapjava.server.impl.http.HomekitClientConnection;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BinaryHandler extends ByteToMessageCodec<ByteBuf> {

  private static final Logger logger = LoggerFactory.getLogger(BinaryHandler.class);

  private final HomekitClientConnection connection;
  private boolean started = false;

  public BinaryHandler(HomekitClientConnection connection) {
    this.connection = connection;
  }

  @Override
  protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    if (started) {
      byte[] b = new byte[msg.readableBytes()];
      msg.readBytes(b);
      out.writeBytes(connection.encryptResponse(b));
    } else {
      out.writeBytes(msg);
    }
  }

  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    byte[] b = new byte[in.readableBytes()];
    in.readBytes(b);
    byte[] decrypted = connection.decryptRequest(b);
    ByteBuf outBuf = Unpooled.copiedBuffer(decrypted);
    out.add(outBuf);
    started = true;
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    boolean errorLevel = !(cause instanceof IOException);
    if (errorLevel) {
      logger.warn("Exception in binary handler", cause);
    } else {
      logger.debug("Exception in binary handler", cause);
    }
    super.exceptionCaught(ctx, cause);
  }
}

@@ -296,24 +296,66 @@
 OException;%0A
+import java.nio.charset.StandardCharsets;%0A
 import java.
@@ -365,16 +365,16 @@
 l.List;%0A
-
 import o
@@ -886,24 +886,67 @@
 (started) %7B%0A
+      debugData(%22Sending data%22, msg, ctx);%0A
       byte%5B%5D
@@ -1395,16 +1395,61 @@
 ypted);%0A
+    debugData(%22Received data%22, outBuf, ctx);%0A
     out.
@@ -1805,16 +1805,16 @@
 ;%0A    %7D%0A
-
     supe
@@ -1847,11 +1847,325 @@
 se);%0A  %7D
+%0A%0A  private void debugData(String msg, ByteBuf b, ChannelHandlerContext ctx) throws Exception %7B%0A    if (logger.isDebugEnabled()) %7B%0A      logger.debug(%0A          String.format(%0A              %22%25s %5B%25s%5D:%25n%25s%22,%0A              msg, ctx.channel().remoteAddress().toString(), b.toString(StandardCharsets.UTF_8)));%0A    %7D%0A  %7D
 %0A%7D%0A

put debugData back