package cn.com.qmth.stmms.common.session.service.impl;

import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.session.service.SessionService;
import cn.com.qmth.stmms.common.utils.AesUtils;
import cn.com.qmth.stmms.common.utils.HessianUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class CookieSessionServiceImpl implements SessionService {

    private static Logger log = LoggerFactory.getLogger(CookieSessionServiceImpl.class);

    private static final int COOKIE_MAX_AGE = 3600 * 10;

    //private static final String COOKIE_DOMAIN = "";

    private static final String COOKIE_PATH = "/";

    private static final String COOKIE_NAME = "stmms_cookie";

    @Override
    public void put(HttpServletRequest request, HttpServletResponse response, StmmsSession ss) {
        if (ss.isInvalid()) {
            remove(request, response);
        } else {
            try {
                ss.setId(request.getSession().getId());
                setCookie(response, COOKIE_NAME, AesUtils.encrypt(HessianUtils.serialize(ss)), COOKIE_MAX_AGE);
            } catch (Exception e) {
                log.error("CookieSessionServiceImpl-put", e);
                remove(request, response);
            }
        }
    }

    @Override
    public StmmsSession get(HttpServletRequest request) {
        StmmsSession session = new StmmsSession();
        Cookie cookie = getCookie(request, COOKIE_NAME);
        try {
            session = (StmmsSession) HessianUtils.deserialize(AesUtils.decrypt(cookie.getValue()));
            if (!session.getId().equals(request.getSession().getId())) {
                session.clear();
            }
        } catch (Exception e) {
            if (session == null) {
                session = new StmmsSession();
            }
        }
        return session;
    }

    @Override
    public void remove(HttpServletRequest request, HttpServletResponse response) {
        setCookie(response, COOKIE_NAME, "", -1);
    }

    /**
     * 获取COOKIE
     *
     * @param request
     * @param name
     */
    private Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null)
            return null;
        for (int i = 0; i < cookies.length; i++) {
            if (name.equals(cookies[i].getName())) {
                return cookies[i];
            }
        }
        return null;
    }

    /**
     * 设置COOKIE
     *
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    private void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        // cookie.setDomain('.' + COOKIE_DOMAIN);
        cookie.setPath(COOKIE_PATH);
        response.addCookie(cookie);
    }

}
