package cn.com.qmth.stmms.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Set;

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

import cn.com.qmth.stmms.biz.basic.model.Privilege;
import cn.com.qmth.stmms.common.domain.ApiUser;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.session.model.StmmsSession;

/**
 * request临时参数存取
 */
public class RequestUtils {

    private static final String REQUEST_SESSION_KEY = "_stmms_session_key_";

    private static final String REQUEST_WEB_USER_KEY = "web_user";

    private static final String REQUEST_API_USER_KEY = "api_user";

    private static final String REQUEST_OPERATION_LOG_KEY = "operation_log";
    
    private static final String REQUEST_VERSION_NAME="versionName";
    
    private static final String REQUEST_VERSION_DATE="versionDate";
    
    private static final String REQUEST_PRIVILEGES_KEY = "privileges";
    
    private static final String REQUEST_ROLE_PRIVILEGE_CODES_KEY = "role_privilege_codes";

    public static StmmsSession getSession(HttpServletRequest request) {
        Object obj = request.getAttribute(REQUEST_SESSION_KEY);
        if (obj != null && obj instanceof StmmsSession) {
            return (StmmsSession) obj;
        } else {
            StmmsSession session = new StmmsSession();
            setSession(request, session);
            return session;
        }
    }

    public static void setSession(HttpServletRequest request, StmmsSession session) {
        request.setAttribute(REQUEST_SESSION_KEY, session);
    }

    public static WebUser getWebUser(HttpServletRequest request) {
        Object obj = request.getAttribute(REQUEST_WEB_USER_KEY);
        if (obj != null && obj instanceof WebUser) {
            return (WebUser) obj;
        } else {
            return null;
        }
    }

    public static void setWebUser(HttpServletRequest request, WebUser user) {
        request.setAttribute(REQUEST_WEB_USER_KEY, user);
        request.setAttribute(REQUEST_VERSION_DATE, VersionInfo.DATE);
        request.setAttribute(REQUEST_VERSION_NAME, VersionInfo.NAME);
    }

    public static ApiUser getApiUser(HttpServletRequest request) {
        Object obj = request.getAttribute(REQUEST_API_USER_KEY);
        if (obj != null && obj instanceof ApiUser) {
            return (ApiUser) obj;
        } else {
            return null;
        }
    }

    public static void setApiUser(HttpServletRequest request, ApiUser user) {
        request.setAttribute(REQUEST_API_USER_KEY, user);
    }

    /**
     * 设置 Cookie
     *
     * @param name
     *            名称
     * @param value
     *            值
     * @param maxAge
     *            生存时间（单位秒）
     */
    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        try {
            cookie.setValue(URLEncoder.encode(value, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addCookie(cookie);
    }

    /**
     * 获得指定Cookie的值
     *
     * @param name
     *            名称
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, String name) {
        return getCookie(request, null, name, false);
    }

    /**
     * 获得指定Cookie的值，并删除。
     *
     * @param name
     *            名称
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        return getCookie(request, response, name, true);
    }

    /**
     * 获得指定Cookie的值
     *
     * @param request
     *            请求对象
     * @param response
     *            响应对象
     * @param name
     *            名字
     * @param isRemove
     *            是否移除
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name,
            boolean isRemove) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    try {
                        value = URLDecoder.decode(cookie.getValue(), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    if (isRemove) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }
        }
        return value;
    }

    public static String getLog(HttpServletRequest request) {
        Object obj = request.getAttribute(REQUEST_OPERATION_LOG_KEY);
        if (obj != null && obj instanceof String) {
            return (String) obj;
        } else {
            return "";
        }
    }

    public static void setLog(HttpServletRequest request, String content) {
        request.setAttribute(REQUEST_OPERATION_LOG_KEY, content);
    }
    
    public static void setRolePrivilegeCodes(HttpServletRequest request, Set<String> privilegeCodes) {
        request.setAttribute(REQUEST_ROLE_PRIVILEGE_CODES_KEY, privilegeCodes);
    }
    
    public static void setPrivileges(HttpServletRequest request, List<Privilege> privileges) {
        request.setAttribute(REQUEST_PRIVILEGES_KEY, privileges);
    }
}