package top.octopusyan.http.config;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.octopusyan.http.EasyHttp;
import top.octopusyan.http.HttpConfig;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description :  网络请求日志打印默认实现
 * @create : 2022-4-2 00:13
 */
public final class LogStrategy implements ILogStrategy {

    public static String TAG = null;
    public static Logger logger = null;

    @Override
    public void print(String log) {
        String logTag = HttpConfig.getInstance().getLogTag();
        if(logger == null || !logTag.equals(TAG)){
            logger = LoggerFactory.getLogger(logTag);
            TAG = logTag;
        }

        logger.info(log != null ? log : "null");
    }

    @Override
    public void json(String json) {
        String text = ILogStrategy.formatJson(json);
        if (StringUtils.isEmpty(text)) {
            return;
        }

        // 打印 Json 数据最好换一行再打印会好看一点
        text = " \n" + text;

        int segmentSize = 3 * 1024;
        long length = text.length();
        if (length <= segmentSize) {
            // 长度小于等于限制直接打印
            print(text);
            return;
        }

        // 循环分段打印日志
        while (text.length() > segmentSize) {
            String logContent = text.substring(0, segmentSize);
            text = text.replace(logContent, "");
            print(logContent);
        }

        // 打印剩余日志
        print(text);
    }

    @Override
    public void print(String key, String value) {
        print(key + " = " + value);
    }

    @Override
    public void print(Throwable throwable) {
        logger.info(HttpConfig.getInstance().getLogTag(), throwable.getMessage(), throwable);
    }

    @Override
    public void print(StackTraceElement[] stackTrace) {
        for (StackTraceElement element : stackTrace) {
            // 获取代码行数
            int lineNumber = element.getLineNumber();
            // 获取类的全路径
            String className = element.getClassName();
            if (lineNumber <= 0 || className.startsWith(EasyHttp.class.getPackage().getName())) {
                continue;
            }

            print("RequestCode = (" + element.getFileName() + ":" + lineNumber + ") ");
            break;
        }
    }
}
