package cn.reghao.autodop.common.docker.unixdomain;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;

/**
 * @author reghao
 * @date 2020-01-14 22:32:58
 */
@Slf4j
public class HttpClientHandler extends ChannelInboundHandlerAdapter {
    private ChannelHandlerContext context;
    private ChannelPromise promise;
    private FullHttpResponse response;

    public ChannelPromise sendRequest(FullHttpRequest request) {
        int count = 5;
        // 禁止无限循环
        while (context == null && count > 0) {
            try {
                // 等待 5s 建立 channel，超时则结束
                Thread.sleep(1_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count--;
        }

        if (context == null) {
            return null;
        }

        promise = context.newPromise();
        context.writeAndFlush(request);
        return promise;
    }

    public FullHttpResponse response() {
        return response;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpResponse) {
            response = (FullHttpResponse) msg;
            int statusCode = response.status().code();
            // 不返回 1xx 响应
            if (statusCode >= HttpResponseStatus.OK.code()) {
                promise.setSuccess();
            }
        } else {
            log.info("Not FullHttpResponse -> {}", msg.getClass());
            System.out.println(msg.getClass());
        }
    }
}
