package com.cm.central.control.client.socket.service.socket.ping;

import com.cm.central.control.client.socket.config.properties.SocketClientProperties;
import com.cm.central.control.client.socket.service.socket.BaseSocketService;
import com.cm.socket.enums.SocketMessageEnum;
import com.cm.socket.enums.SocketTypeMessageEnum;
import com.cm.socket.pojo.Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: PingServiceImpl
 * @Description: PING业务
 * @Author: WangGeng
 * @Date: 2020/7/29 10:51 上午
 * @Version: 1.0
 **/
@Component("pingServiceImpl")
public class PingServiceImpl extends BaseSocketService {

    @Autowired
    private SocketClientProperties socketClientProperties;

    @Override
    protected void readMessageService(ChannelHandlerContext channelHandlerContext, Message readMessage) {
        System.out.println(readMessage.getToken() + ": " + readMessage.getContent());
    }

    @Override
    public void autoReply(ChannelHandlerContext channelHandlerContext) {
        Channel channel = channelHandlerContext.channel();
        ScheduledFuture<?> scheduledFuture = channel.eventLoop().schedule(() -> {
            if (channel.isActive()) {
                writeMessage(channelHandlerContext, SocketTypeMessageEnum.MESSAGE_TYPE_PING, SocketMessageEnum.MESSAGE_PING.getMessage());
            } else {
                channelHandlerContext.close();
                throw new RuntimeException();
            }
        }, socketClientProperties.getDelayPingSeconds(), TimeUnit.SECONDS);
        scheduledFuture.addListener(future -> {
            if (future.isSuccess()) {
                autoReply(channelHandlerContext);
            }
        });
    }
}
