package com.cm.central.control.client.socket.handler;

import com.cm.central.control.client.socket.config.properties.SocketClientProperties;
import com.cm.central.control.client.socket.socket.SocketClientRunnable;
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 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: MessageClientChannelInitializer
 * @Description: 消息客户端初始化
 * @Author: WangGeng
 * @Date: 2020/7/6 9:32 上午
 * @Version: 1.0
 **/
@Component
public class SocketClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private SocketClientRunnable socketClientRunnable;
    @Autowired
    private SocketClientProperties socketClientProperties;
    @Resource(name = "pingServiceImpl")
    private ISocketService pingServiceImpl;
    @Resource(name = "clientInfoServiceImpl")
    private ISocketService clientInfoServiceImpl;
    @Resource(name = "exceptionServiceImpl")
    private ISocketService exceptionServiceImpl;
    @Resource(name = "loginServiceImpl")
    private ISocketService loginServiceImpl;
    @Resource(name = "errorServiceImpl")
    private ISocketService errorServiceImpl;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new MessageEncoder());
        ch.pipeline().addLast(new MessageDecoder());
        ch.pipeline().addLast(getSocketClientHandler());
    }

    /**
     * 获取消息处理器
     *
     * @return
     */
    private SocketClientHandler getSocketClientHandler() {
        SocketClientHandler socketClientHandler = new SocketClientHandler();
        socketClientHandler.setClientInfoServiceImpl(clientInfoServiceImpl);
        socketClientHandler.setExceptionServiceImpl(exceptionServiceImpl);
        socketClientHandler.setLoginServiceImpl(loginServiceImpl);
        socketClientHandler.setPingServiceImpl(pingServiceImpl);
        socketClientHandler.setErrorServiceImpl(errorServiceImpl);
        socketClientHandler.setSocketClientProperties(socketClientProperties);
        socketClientHandler.setSocketClientRunnable(socketClientRunnable);
        return socketClientHandler;
    }

}
