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

import com.alibaba.fastjson.JSONObject;
import com.cm.central.control.client.socket.manager.SocketClientManager;
import com.cm.central.control.client.socket.service.socket.BaseSocketService;
import com.cm.socket.consts.ISocketConst;
import com.cm.socket.enums.SocketTypeMessageEnum;
import com.cm.socket.pojo.Message;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Service;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: ExceptionServiceImpl
 * @Description: 异常业务
 * @Author: WangGeng
 * @Date: 2020/7/29 2:41 下午
 * @Version: 1.0
 **/
@Service("exceptionServiceImpl")
public class ExceptionServiceImpl extends BaseSocketService {

    @Override
    protected void readMessageService(ChannelHandlerContext channelHandlerContext, Message readMessage) {

    }

    @Override
    public void autoReply(ChannelHandlerContext channelHandlerContext) {

    }

    /**
     * 发送异常信息
     *
     * @param throwable
     */
    public void writeThrowable(Throwable throwable) {
        SocketClientManager socketClientManager = SocketClientManager.getInstance();
        if (socketClientManager.getChannel() == null) {
            LOG.debug("Socket客户端未登录，不发送异常信息...");
            return;
        }

        StringBuffer exceptionSB = new StringBuffer();
        exceptionSB.append(throwable).append("\n");
        StackTraceElement[] stackTrace = throwable.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            exceptionSB.append("\tat " + stackTraceElement).append("\n");
        }

        JSONObject exceptionJSONObject = new JSONObject();
        exceptionJSONObject.put(ISocketConst.EXCEPTION_CLASS, throwable.getClass().getName());
        exceptionJSONObject.put(ISocketConst.EXCEPTION_MESSAGE, throwable.getMessage());
        exceptionJSONObject.put(ISocketConst.EXCEPTION_CONTENT, exceptionSB.toString());

        Message message = new Message();
        message.setStart(SocketTypeMessageEnum.MESSAGE_TYPE_START.getType());
        message.setType(SocketTypeMessageEnum.MESSAGE_TYPE_EXCEPTION.getType());
        message.setToken(socketClientManager.getToken());
        try {
            message.setContent(getEncodeContent(JSONObject.toJSONString(successResult(exceptionJSONObject))));
            socketClientManager.getChannel().writeAndFlush(message);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

}