package com.apobates.forum.thrones;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration;
import org.springframework.session.jdbc.config.annotation.web.http.EnableJdbcHttpSession;
import org.springframework.session.jdbc.config.annotation.web.http.JdbcHttpSessionConfiguration;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.session.web.http.HttpSessionIdResolver;

/**
 * Spring session的配置文件
 * 
 * @author xiaofanku
 * @since 20200602
 */
@Configuration
@EnableJdbcHttpSession
public class SpringSessionConfig {
    //@see https://stackoverflow.com/questions/33095345/how-to-change-spring-session-redis-cookie-name
    //"SESSION" name is a default set in source of CookieHttpSessionStrategy.
    @Autowired
    private Environment env;
    
    @Bean
    public SpringHttpSessionConfiguration init() {
        JdbcHttpSessionConfiguration config = new org.springframework.session.jdbc.config.annotation.web.http.JdbcHttpSessionConfiguration();
        config.setTableName(env.getProperty("site.session.spring.table"));
        return config;
    }
    //@see https://blog.csdn.net/zhu124866/article/details/99698986
    //@see https://docs.spring.io/spring-session/docs/current/reference/html5/guides/java-custom-cookie.html
    //Cookie配置
    @Bean
    public CookieSerializer cookieSerializer(){
        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
        cookieSerializer.setCookieName(env.getProperty("site.session.spring.symbol"));//sessionId名称
        return  cookieSerializer;
    }
    
    //HttpSessionId配置
    @Bean
    public HttpSessionIdResolver httpSessionIdResolver(){
        CookieHttpSessionIdResolver cookieHttpSessionIdResolver = new CookieHttpSessionIdResolver();
        cookieHttpSessionIdResolver.setCookieSerializer(cookieSerializer());
        return cookieHttpSessionIdResolver;
    }
}