package cn.freemud.controller;

import ch.qos.logback.classic.Level;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@RestController
public class TestExceptionController {
    private static Logger logger = LoggerFactory.getLogger(TestExceptionController.class);

    @RequestMapping(value = "test/exception")
    public void test() {
        try {
            throw new NullPointerException();
        }catch (Exception e) {
            ErrorLog.infoConvertJson(this.getClass(),"testException1", e);
            infoConvertJson(this.getClass(), "testExceptionV2", e);
            infoConvertJson2(this.getClass(), "testExceptionV3", e);
            infoConvertJson3(this.getClass(), "testExceptionV4", e);
        }
    }

    public static void infoConvertJson(Class logClass, String message, Exception ex) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ex.printStackTrace(new PrintStream(baos));
        String exception = baos.toString();
        printLog(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), logClass, message, exception, Level.ERROR);
    }


    public static void printLog(String appName, String trackingNo, Class logClass, String message, Object object, Level level) {
        logger.error("appName:{} trackingNo:{} className{} level:{} messasge:{} stackTrack:{}", appName, trackingNo, logClass, level.levelStr, message, object);
    }

    public static void infoConvertJson2(Class logClass, String message, Exception ex) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ex.printStackTrace(new PrintStream(baos));
        String exception = baos.toString();
        exception = StringUtils.replace(exception, "\\t", "");
        printLog(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), logClass, message, exception, Level.ERROR);
    }

    public static void infoConvertJson3(Class logClass, String message, Exception ex) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ex.printStackTrace(new PrintStream(baos));
        String exception = baos.toString();
        exception = StringUtils.replace(exception, "\\n\\t", ",");
        printLog(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), logClass, message, exception, Level.ERROR);
    }

}
