package com.cm.central.control.handler;

import com.cm.central.control.config.properties.SocketServerProperties;
import com.cm.central.control.trigger.SocketServerIdleStateTrigger;
import com.cm.socket.decoder.MessageDecoder;
import com.cm.socket.encoder.MessageEncoder;
import com.cm.socket.service.ISocketService;
import io.netty.channel.ChannelInitializer;
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 javax.annotation.Resource;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: MessageServerChannelInitializer
 * @Description: 消息服务初始化通道
 * @Author: WangGeng
 * @Date: 2020/7/4 17:05
 * @Version: 1.0
 **/
@Component
public class SocketServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private SocketServerProperties socketServerProperties;
    @Resource(name = "socketPongServiceImpl")
    private ISocketService socketClientPongServiceImpl;
    @Resource(name = "socketExceptionServiceImpl")
    private ISocketService socketClientExceptionServiceImpl;
    @Resource(name = "socketLoginServiceImpl")
    private ISocketService socketClientLoginServiceImpl;
    @Resource(name = "socketClientInfoServiceImpl")
    private ISocketService socketClientInfoServiceImpl;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // 5s没没有收到客户端的信息，断开连接
        ch.pipeline().addLast(new IdleStateHandler(socketServerProperties.getReadIdleTimeSecond(), 0, 0));
        ch.pipeline().addLast(new SocketServerIdleStateTrigger());
        ch.pipeline().addLast(new MessageEncoder());
        ch.pipeline().addLast(new MessageDecoder());
        ch.pipeline().addLast(getSocketServerHandler());
    }

    /**
     * 获取socket server handler
     *
     * @return
     */
    private SocketServerHandler getSocketServerHandler() {
        SocketServerHandler socketServerHandler = new SocketServerHandler();
        socketServerHandler.setSocketClientPongServiceImpl(socketClientPongServiceImpl);
        socketServerHandler.setSocketClientExceptionServiceImpl(socketClientExceptionServiceImpl);
        socketServerHandler.setSocketClientLoginServiceImpl(socketClientLoginServiceImpl);
        socketServerHandler.setSocketClientInfoServiceImpl(socketClientInfoServiceImpl);
        return socketServerHandler;
    }

}
