package de.avatic.taric.config;

import de.avatic.taric.serializer.DescSetSerializer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LanguageInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        String lang = request.getParameter("lang");
        if (lang == null) {
            lang = request.getHeader("Accept-Language");
            if (lang != null && lang.length() >= 2) {
                lang = lang.substring(0, 2).toUpperCase();
            }
        }
        DescSetSerializer.setLanguage(lang);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        DescSetSerializer.clearLanguage();
    }
}