package com.apobates.forum.member.storage.cookie;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.member.storage.core.MemberSessionBeanConverter;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.CookieUtils;
/**
 * 使用Cookie存储会员在线信息,信息使用BASE64编码
 * OnlineMemberCookieStorage的子类
 * 
 * @author xiaofanku
 * @since 20191231
 */
public class HttpCookieProvider extends OnlineMemberCookieStorage{
    public HttpCookieProvider(CookieMetaConfig metaConfig) {
        super(metaConfig);
    }
    
    private static Map<String, String> toMap(String base64String) {
        String memberSerialJSON = CookieUtils.decodeCookieValue(base64String, OnlineMemberCookieStorage.NP);
        if(OnlineMemberCookieStorage.NP.equals(memberSerialJSON)){
            return Collections.emptyMap();
        }
        return Commons.fromString(memberSerialJSON);
    }
    
    @Override
    protected Map<String, String> restoreMapForCookie(HttpServletRequest request) {
        Cookie cookie = CookieUtils.queryCookie(request, getMetaConfig().getName()).orElse(null);
        if (null == cookie) {
            return Collections.emptyMap();
        }
        StorageSerialize ss = StorageSerialize.getInstance(cookie.getValue()); //可能有异常出来@20200120
        return toMap(ss.getHash());
    }
    
    @Override
    protected Map<String, String> generateCookieMap(MemberSessionBean memberSessionBean, LocalDateTime expireDate) {
        return MemberSessionBeanConverter.toMap(memberSessionBean, expireDate);
    }
}
