package com.nokia.service.handler;

import java.util.concurrent.CompletableFuture;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理鉴权消息
 * 通过CompletableFuture<Boolean>
 */
@Slf4j
public class AuthHandler extends SimpleChannelInboundHandler<String> {

    private final String userName;
    private final String password;
    private final CompletableFuture<Boolean> future;

    public AuthHandler(String userName, String password, CompletableFuture<Boolean> future) {
        this.userName = userName;
        this.password = password;
        this.future = future;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 处理鉴权结果
        msg = msg.trim();
        if (msg.startsWith("<ConnectACK>")) {
            int index = msg.indexOf("VerifyResult:0");
            if (index > 0) {
                // 鉴权成功，删除鉴权处理器
                ctx.pipeline().remove(this);
                future.complete(true);
            }
        } else {
            log.error("鉴权失败，返回消息：{}", msg.replaceAll("\r\n", ""));
            ctx.close();
            future.complete(false);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送鉴权消息
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<Connect>\r\nUserName:")
                .append(userName).append("\r\nPassword:")
                .append(password).append("\r\n</Connect>\r\n");
        ctx.writeAndFlush(stringBuffer.toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
        future.complete(false);
    }

}
