/*
 * 文 件 名:  ChargingPileChannelInitializer
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  充电桩通道初始化器
 * 修 改 人:  lvwenbin
 * 修改时间:  2025/12/22
 */
package com.ruoyi.ems.charging.core;

import com.ruoyi.ems.charging.handler.ChargingPileMessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 充电桩通道初始化器
 * 配置Netty Channel Pipeline
 *
 * @author lvwenbin
 * @version [版本号, 2025/12/22]
 */
@Component
public class ChargingPileChannelInitializer extends ChannelInitializer<SocketChannel> {
    
    /**
     * 读空闲超时时间(秒) - 3次心跳间隔
     */
    private static final int READER_IDLE_TIME = 35;
    
    /**
     * 写空闲超时时间(秒)
     */
    private static final int WRITER_IDLE_TIME = 0;
    
    /**
     * 读写空闲超时时间(秒)
     */
    private static final int ALL_IDLE_TIME = 0;
    
    @Autowired
    private ChargingPileMessageHandler messageHandler;
    
    @Autowired
    private IdleStateEventHandler idleStateEventHandler;
    
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        
        // 日志处理器(调试用，生产环境可移除)
        // pipeline.addLast("logging", new LoggingHandler(LogLevel.DEBUG));
        
        // 空闲状态检测处理器
        pipeline.addLast("idleStateHandler", 
            new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME, TimeUnit.SECONDS));
        pipeline.addLast("idleEventHandler", idleStateEventHandler);
        
        // 协议解码器
        pipeline.addLast("decoder", new ChargingPileDecoder());
        
        // 协议编码器
        pipeline.addLast("encoder", new ChargingPileEncoder());
        
        // 业务消息处理器
        pipeline.addLast("messageHandler", messageHandler);
    }
}
