package com.emato.ich.utils;

import com.emato.ich.contant.ExceptionType;
import com.emato.ich.entity.vo.ExceptionVo;
import com.emato.ich.message.ICHPublishClient;
import com.emato.ich.message.ICHTopic;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.ByteArrayOutputStream;
import java.util.Date;

/**
 * 异常日志处理工具类
 */
public class LoggingUtils {


    public static void sendErrorLog(String cause, Throwable throwable){

        MqttMessage mqttMessage = wrapMessage((cause + ": " + (getStackTrace(throwable).toString())), ExceptionType.BIZ_ERROR);
        ICHPublishClient.getInstance().publish(String.format(ICHTopic.ERROR_LOG_REPORT, BaseUtils.getClientId()), mqttMessage);
    }

    public static void sendAppErrorLog(String cause, Throwable throwable){

        MqttMessage mqttMessage = wrapMessage((cause + ": " + (getStackTrace(throwable).toString())), ExceptionType.CRASH_ERROR);
        ICHPublishClient.getInstance().publish(String.format(ICHTopic.ERROR_LOG_REPORT, BaseUtils.getClientId()), mqttMessage);
    }

    private static MqttMessage wrapMessage(String cause, String type) {
        ExceptionVo exceptionVo = new ExceptionVo();
        exceptionVo.setClientId(BaseUtils.getClientId());
        exceptionVo.setReportData(cause);
        exceptionVo.setReportType(type);
        exceptionVo.setReportTime(DateUtils.formatDate(new Date()));
        // TODO 发送异常信息
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(1);
        byte[] bytes = null;
        try {
            bytes = JacksonUtils.objectmapper.writeValueAsBytes(exceptionVo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        mqttMessage.setPayload(bytes);
        return mqttMessage;
    }


    private static ByteArrayOutputStream getStackTrace(Throwable t) {
        ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream();
        t.printStackTrace(new java.io.PrintWriter(buf, true));
        return buf;
    }

}
