package eu.dnetlib.openaire.usermanagement.authorization;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

@Configuration
@EnableRedisHttpSession
public class Config {

    private static Logger logger = Logger.getLogger(Config.class);

    @Value("${redis.host:localhost}")
    private String host;

    @Value("${redis.port:6379}")
    private String port;

    @Value("${redis.password:#{null}}")
    private String password;

    @Value("${webbapp.front.domain:.openaire.eu}")
    private String domain;

    @Bean
    public LettuceConnectionFactory connectionFactory() {
        logger.info(String.format("Redis connection listens to %s:%s ",host,port));
        LettuceConnectionFactory factory = new LettuceConnectionFactory(host,Integer.parseInt(port));
        if(password != null) factory.setPassword(password);
        return factory;
    }

    @Bean
    public CookieSerializer cookieSerializer() {
        logger.info("Cookie Serializer: Domain is "+domain);
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("openAIRESession"); // <1>
        serializer.setCookiePath("/"); // <2>
//        serializer.setDomainNamePattern(""); //with value "" set's the domain of the service e.g scoobydoo.di.uoa.gr
        serializer.setDomainName(domain);
        return serializer;
    }
}
