package thyyxxk.webserver.utils;

import com.auth0.jwt.JWT;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author dj
 */
@Component
public class TokenUtil {
    private TokenUtil() {
    }

    private static volatile TokenUtil INSTANCE = null;

    public static TokenUtil getInstance() {
        if (null == INSTANCE) {
            synchronized (TokenUtil.class) {
                if (null == INSTANCE) {
                    INSTANCE = new TokenUtil();
                }
            }
        }
        return INSTANCE;
    }

    public String getTokenUserId() {
        try {
            String token = Objects.requireNonNull(getRequest()).getHeader("token");
            return JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            return "99999";
        }
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }
}
