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

import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apobates.forum.member.entity.MemberGroupEnum;
import com.apobates.forum.member.entity.MemberRoleEnum;
import com.apobates.forum.member.entity.MemberStatusEnum;
import com.apobates.forum.member.storage.MetaConfig;
import com.apobates.forum.member.storage.OnlineMemberStorage;
import com.apobates.forum.member.storage.core.MemberSessionBean;
/**
 * 使用Session存储会员在线信息
 * 
 * @author xiaofanku
 * @since 20200101
 */
public class OnlineMemberSessionStorage implements OnlineMemberStorage{
	private final MetaConfig metaConfig;
	private final static Logger logger = LoggerFactory.getLogger(OnlineMemberSessionStorage.class);
	
	public OnlineMemberSessionStorage(MetaConfig metaConfig) {
		super();
		this.metaConfig = metaConfig;
	}
	
	@Override
	public void store(MemberSessionBean memberSessionBean, HttpServletRequest request, HttpServletResponse response) {
		request.getSession().invalidate();
		HttpSession s = request.getSession(true);
		s.setAttribute(metaConfig.getName(), memberSessionBean);
	}
	
	@Override
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		HttpSession s = request.getSession();
		s.removeAttribute(metaConfig.getName());
		s.invalidate();
		
	}
	
	@Override
	public Optional<MemberSessionBean> getInstance(HttpServletRequest request, String sentinel) {
		MemberSessionBean mbean = null;
		try{
			mbean = (MemberSessionBean) request.getSession().getAttribute(metaConfig.getName());
		}catch(Exception e){
			if(logger.isDebugEnabled()){
				logger.debug("[OM][SS]get session msb fail, exception: "+e.getMessage(), e);
			}
		}
		return Optional.ofNullable(mbean);
	}
	
	@Override
	public void refresh(HttpServletRequest request, HttpServletResponse response, MemberStatusEnum status, MemberGroupEnum group, MemberRoleEnum role) {
		try{
			MemberSessionBean mbean = (MemberSessionBean) request.getSession().getAttribute(metaConfig.getName());
			request.getSession().setAttribute(metaConfig.getName(), mbean.refact(group, role, status));
		}catch(Exception e){
			if(logger.isDebugEnabled()){
				logger.debug("[OM][SS]get session msb fail, exception: "+e.getMessage(), e);
			}
		}
	}
	
	@Override
	public boolean isSupportRevival() {
		return true;
	}
	
	@Override
	public MetaConfig getMetaConfig() {
		return metaConfig;
	}
}
