package com.tzld.piaoquan.recommend.server.util;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.net.InetAddress;

/**
 * @author dyp
 */
public class TraceUtils {
    public static final String TRACE_ID_KEY = "traceId";
    public static final String DEFAULT_TRACE_ID = "default_trace_id";

    public static void setMDC() {
        MDC.put(TraceUtils.TRACE_ID_KEY, genTraceId());
    }

    public static String currentTraceId() {
        return MDC.get(TraceUtils.TRACE_ID_KEY);
    }

    public static void removeMDC() {
        MDC.remove(TraceUtils.TRACE_ID_KEY);
    }

    public static String genTraceId() {
        StringBuilder traceIdBuilder = new StringBuilder();
        InetAddress address = InetAddress.getLoopbackAddress();
        if (address == null) {
            return DEFAULT_TRACE_ID;
        }
        String addressStr = address.getHostAddress();
        if (StringUtils.isBlank(addressStr)) {
            return DEFAULT_TRACE_ID;
        }
        String[] addressArr = addressStr.split("\\.");
        if (addressArr.length != 4) {
            return DEFAULT_TRACE_ID;
        }

        traceIdBuilder.append(StringUtils.leftPad(Integer.toHexString(Integer.valueOf(addressArr[0])), 2, '0'))
                .append(StringUtils.leftPad(Integer.toHexString(Integer.valueOf(addressArr[1])), 2, '0'))
                .append(StringUtils.leftPad(Integer.toHexString(Integer.valueOf(addressArr[2])), 2, '0'))
                .append(StringUtils.leftPad(Integer.toHexString(Integer.valueOf(addressArr[3])), 2, '0'))
                .append(System.currentTimeMillis())
                .append(RandomStringUtils.randomAlphabetic(4))
                .append(Thread.currentThread().getId());
        return traceIdBuilder.toString();
    }
}
