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

import com.cm.central.control.client.socket.manager.SocketClientManager;
import com.cm.central.control.client.socket.service.BaseService;
import com.cm.socket.enums.SocketTypeMessageEnum;
import com.cm.socket.pojo.Message;
import com.cm.socket.service.AbstractSocketService;
import com.cm.socket.service.ISocketService;
import io.netty.channel.ChannelHandlerContext;

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

    @Override
    public void readMessage(ChannelHandlerContext channelHandlerContext, Message readMessage) throws Exception {
        readMessageService(channelHandlerContext, readMessage);
    }

    @Override
    protected abstract void readMessageService(ChannelHandlerContext channelHandlerContext, Message readMessage) throws Exception;

    /**
     * 输出信息
     *
     * @param channelHandlerContext
     * @param socketTypeMessageEnum
     * @param content
     */
    @Override
    public void writeMessage(ChannelHandlerContext channelHandlerContext, SocketTypeMessageEnum socketTypeMessageEnum, String content) {
        Message message = new Message();
        message.setStart(SocketTypeMessageEnum.MESSAGE_TYPE_START.getType());
        message.setType(socketTypeMessageEnum.getType());
        message.setToken(SocketClientManager.getInstance().getToken());
        message.setContent(content);
        write(channelHandlerContext, message);
    }

    /**
     * 输出错误信息
     *
     * @param channelHandlerContext
     * @param errorMessage
     */
    @Override
    public void writeError(ChannelHandlerContext channelHandlerContext, String errorMessage) {
        Message message = new Message();
        message.setStart(SocketTypeMessageEnum.MESSAGE_TYPE_START.getType());
        message.setType(SocketTypeMessageEnum.MESSAGE_TYPE_ERROR.getType());
        message.setToken(SocketClientManager.getInstance().getToken());
        message.setContent(errorMessage);
        write(channelHandlerContext, message);
    }

    /**
     * 输出数据
     *
     * @param channelHandlerContext
     * @param writeMessage
     */
    @Override
    protected void write(ChannelHandlerContext channelHandlerContext, Message writeMessage) {
        channelHandlerContext.channel().writeAndFlush(writeMessage);
    }

}
