package org.framework.lazy.cloud.network.heartbeat.common.allocator;

import io.netty.channel.DefaultMaxMessagesRecvByteBufAllocator;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.RecvByteBufAllocator;
import lombok.extern.slf4j.Slf4j;

import static io.netty.util.internal.ObjectUtil.checkPositive;

/**
 * The {@link RecvByteBufAllocator} that always yields the same buffer
 * size prediction.  This predictor ignores the feed back from the I/O thread.
 * 接收数据缓冲区
 *
 * @see FixedRecvByteBufAllocator
 */
@Slf4j
public class NettyRecvByteBufAllocator extends DefaultMaxMessagesRecvByteBufAllocator {

    private final int bufferSize;

    private final class HandleImpl extends MaxMessageHandle {
        private final int bufferSize;

        HandleImpl(int bufferSize) {
            this.bufferSize = bufferSize;
        }

        @Override
        public int guess() {
//            log.info("guess :{}", bufferSize);
            return bufferSize;
        }

        @Override
        public void attemptedBytesRead(int bytes) {
//            log.info("attemptedBytesRead:{}", bytes);
            super.attemptedBytesRead(bytes);
        }

        @Override
        public int attemptedBytesRead() {
            int attemptedBytesRead = super.attemptedBytesRead();
//            log.info("attemptedBytesRead result:{}", attemptedBytesRead);
            return attemptedBytesRead;
        }

        @Override
        public void lastBytesRead(int bytes) {
            super.lastBytesRead(bytes);
//            log.info("lastBytesRead result:{}", bytes);
        }
    }

    /**
     * Creates a new predictor that always returns the same prediction of
     * the specified buffer size.
     */
    public NettyRecvByteBufAllocator(int bufferSize) {
//        checkPositive(bufferSize, "bufferSize");
        this.bufferSize = bufferSize;
    }

    @SuppressWarnings("deprecation")
    @Override
    public Handle newHandle() {
        return new NettyRecvByteBufAllocator.HandleImpl(bufferSize);
    }

    @Override
    public NettyRecvByteBufAllocator respectMaybeMoreData(boolean respectMaybeMoreData) {
        super.respectMaybeMoreData(respectMaybeMoreData);
        return this;
    }
}
