package ${basePackage}.frame.auth;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import ${basePackage}.frame.auth.Token;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LocalData - 本地数据存放类
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
public class LocalData {

    private static ApplicationContext applicationContext = null;

    private static Token system = null;

    static {
        // 组装系统Token
        system = new Token();
        system.setId(0);
        system.setUserId(0);
        system.setUserName("system");
        system.putRes(".*");
    }

    public static Token getSysToken() {
        return system;
    }

    /**
     * 当请求目标 target = '/aa/bb'
     */
    private static final ThreadLocal<String> actionHolder = new ThreadLocal();

    public static String getAction() {
        return actionHolder.get();
    }

    public static void setAction(String action) {
        actionHolder.set(action);
    }

    /**
     * 当前用户的通行证
     */
    private static final ThreadLocal<Token> tokenHolder = new ThreadLocal();

    public static Token getToken() {
        return tokenHolder.get();
    }

    public static void setToken(Token token) {
        tokenHolder.set(token);
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static ApplicationContext getApplicationContext() {
        return LocalData.applicationContext;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        LocalData.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> t) {
        if (getApplicationContext() == null) {
            return null;
        }
        try {
            return getApplicationContext().getBean(t);
        } catch (BeansException ignored) {
            return null;
        }
    }

    public static Environment getEnvironment() {
        return getBean(Environment.class);
    }
}
