package fr.titionfire.ffsaf.domain.service;

import io.quarkus.websockets.next.WebSocketConnection;
import jakarta.enterprise.context.RequestScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;

import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

@RequestScoped
public class TradService {

    @Inject
    Instance<ContainerRequestContext> requestContextInstance;

    public static final Locale fallbackLocale = Locale.FRANCE;

    public String t(String key) {
        return translate(key);
    }

    public String t(String key, WebSocketConnection connection) {
        List<String> lang = connection.handshakeRequest().headers().get("Accept-Language");
        Locale userLocale = lang != null && !lang.isEmpty() ? Locale.forLanguageTag(lang.get(0)) : fallbackLocale;
        return translate(key, userLocale);
    }

    public String translate(String key) {
        ContainerRequestContext requestContext = requestContextInstance.get();
        Locale userLocale = (Locale) requestContext.getProperty("userLocale");

        return translate(key, userLocale);
    }

    public String translate(String key, Locale userLocale) {
        try {
            ResourceBundle messages = ResourceBundle.getBundle("lang.messages", userLocale);
            return messages.getString(key);
        } catch (MissingResourceException e) {
            try {
                ResourceBundle fallbackMessages = ResourceBundle.getBundle("lang.messages", fallbackLocale);
                return fallbackMessages.getString(key);
            } catch (MissingResourceException ex) {
                return key;
            }
        }
    }
}
