package xyz.wbsite.dbtool.web.frame.auth;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import xyz.wbsite.dbtool.web.frame.base.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 Token temp = null;

    private static Token system = null;

    static {
        // 组装临时Token和系统Token
        temp = new Token();
        temp.setId(-1);
        temp.setUserId(-1);
        temp.setUserName("游客");
        temp.putResource("ajax.system.admin.login");
        system = new Token();
        system.setId(0);
        system.setUserId(0);
        system.setUserName("system");
        system.putResource(".*");
    }

    public static Token getTempToken() {
        return temp;
    }

    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 WebApplicationContextUtils.getWebApplicationContext(getRequest().getServletContext());
    }
}
