package de.assecutor.votianlt.service;

import com.vaadin.flow.component.UI;
import de.assecutor.votianlt.config.TranslationProvider;
import de.assecutor.votianlt.model.Language;
import de.assecutor.votianlt.model.User;
import de.assecutor.votianlt.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Locale;

@Service
public class LanguageService {

    private final UserRepository userRepository;
    private final TranslationProvider translationProvider;

    @Autowired
    public LanguageService(UserRepository userRepository, TranslationProvider translationProvider) {
        this.userRepository = userRepository;
        this.translationProvider = translationProvider;
    }

    public void updateUserLanguage(User user, Language language) {
        user.setLanguage(language);
        userRepository.save(user);
    }

    public Language getUserLanguage(User user) {
        return user.getLanguage();
    }

    public String getTranslation(String key, Language language) {
        return translationProvider.getTranslation(key, language != null ? language : Language.DE);
    }

    public String getTranslation(String key, User user) {
        return getTranslation(key, user.getLanguage());
    }

    public void applyLocaleForUser(User user) {
        if (user != null && user.getLanguage() != null) {
            // Get the UI instance and set the locale
            UI ui = UI.getCurrent();
            if (ui != null) {
                Locale locale = getLocaleFromLanguage(user.getLanguage());
                ui.setLocale(locale);
            }
        }
    }

    private Locale getLocaleFromLanguage(Language language) {
        return switch (language) {
        case DE -> Locale.GERMAN;
        case EN -> Locale.ENGLISH;
        case FR -> Locale.FRENCH;
        case ES -> Locale.of("es", "ES");
        case TR -> Locale.of("tr", "TR");
        case PL -> Locale.of("pl", "PL");
        case RU -> Locale.of("ru", "RU");
        case EE -> Locale.of("et", "EE");
        case LV -> Locale.of("lv", "LV");
        case LT -> Locale.of("lt", "LT");
        default -> Locale.GERMAN;
        };
    }

    public Language getCurrentUserLanguage(User user) {
        return user != null ? user.getLanguage() : Language.DE;
    }
}
