package es.uv.saic.config;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import es.uv.saic.domain.Usuari;
import es.uv.saic.service.UsuariService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Configuration
public class ApplicationLocaleResolver extends SessionLocaleResolver {
    @Autowired
    UsuariService us;

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Locale userLocale = Locale.forLanguageTag("ca"); 
        if(!(securityContext.getAuthentication() instanceof AnonymousAuthenticationToken)) {
        	Usuari usuari = ((Usuari)securityContext.getAuthentication().getPrincipal());
        	String locale = usuari.getLocale();
        	userLocale = locale == null ? userLocale : Locale.forLanguageTag(locale);
        }
        
        return userLocale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        super.setLocale(request, response, locale);

        SecurityContext securityContext = SecurityContextHolder.getContext();
        if(!(securityContext.getAuthentication() instanceof AnonymousAuthenticationToken)) {
        	Usuari usuari = ((Usuari)securityContext.getAuthentication().getPrincipal());
	        usuari.setLocale(locale.toLanguageTag());
	        us.save(usuari);
        }        
    }
}
