package com.inzy.wsmock

import com.inzy.wsmock.push.PushFactory
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame
import io.netty.handler.codec.http.websocketx.WebSocketFrame
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

/**
 * 自定义WebSocket处理器（专注处理消息交互，Channel管理交给ChannelManager）
 */
@Sharable
@Component
class WebSocketHandler(private val pushFactory: PushFactory) : SimpleChannelInboundHandler<WebSocketFrame>() {

//    private val logger = LoggerFactory.getLogger(javaClass)

    // 注入ChannelManager单例
    private val channelManager = ChannelManager.instance

    // 监听握手成功事件（此时RequestParamHandler已解析参数）
    override fun userEventTriggered(ctx: ChannelHandlerContext, evt: Any) {
        if (evt is WebSocketServerProtocolHandler.HandshakeComplete) {
            val channel = ctx.channel()
            // 交给ChannelManager管理
            channelManager.addChannel(channel)
            //根据后缀路径推送
            pushFactory.pushMsgFormPath(channel)

            // 握手成功后读取参数（此时参数已存储）
//            val params = ctx.channel().attr(RequestParamHandler.REQUEST_PARAMS_KEY).get()
//            val path = ctx.channel().attr(RequestParamHandler.REQUEST_PATH_KEY).get()
//            logger.info("WS握手成功，客户端查询参数：$params  请求路径：$path")
//            ctx.writeAndFlush(TextWebSocketFrame("Welcome!"))
//            ctx.writeAndFlush(TextWebSocketFrame("Welcome! Client ID: $clientId, params: $params"))
        }
        super.userEventTriggered(ctx, evt)
    }
    /**
     * 客户端连接成功
     */
    /*    override fun channelActive(ctx: ChannelHandlerContext) {
            val channel = ctx.channel()
            val clientId = channel.id().asShortText()
            // 交给ChannelManager管理
            channelManager.addChannel(channel)
    //        val type = ctx.channel().attr(RequestParamHandler.REQUEST_PARAMS_KEY).get()
    //        println("当前连接的客户端type：$type")
            // 欢迎消息
            channel.writeAndFlush(TextWebSocketFrame("Welcome! Client ID: $clientId"))
        }*/

    /**
     * 客户端断开连接
     */
    override fun channelInactive(ctx: ChannelHandlerContext) {
        val channel = ctx.channel()
        // 交给ChannelManager管理
        channelManager.removeChannel(channel)
    }

    /**
     * 处理客户端消息
     */
    override fun channelRead0(ctx: ChannelHandlerContext, frame: WebSocketFrame) {
        /*        if (frame is TextWebSocketFrame) {
                    val msg = frame.text()
                    val clientId = ctx.channel().id().asShortText()
                    println("收到客户端[$clientId]消息：$msg")
                    // 回复客户端
                    ctx.writeAndFlush(TextWebSocketFrame("Server received: $msg"))
                }*/
    }

    /**
     * 异常处理
     */
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        val channel = ctx.channel()
        val clientId = channel.id().asShortText()
        println("客户端[$clientId]发生异常：${cause.message}")
        ctx.close()
        // 交给ChannelManager移除失效Channel
        channelManager.removeChannel(channel)
    }


    /**
     * 广播消息（复用ChannelManager的实现）
     */
    /* fun broadcastMsg(msg: String) {
         channelManager.broadcastMsg(msg)
     }*/
}