package p.studio.utilities.i18n;

import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

public final class I18nService {
    private final ObjectProperty<Locale> locale = new SimpleObjectProperty<>(Locale.ENGLISH);

    public ObjectProperty<Locale> localeProperty() { return locale; }
    public Locale getLocale() { return locale.get(); }
    public void setLocale(Locale l) { locale.set(l); }

    private ResourceBundle bundle(Locale l) {
        return ResourceBundle.getBundle("i18n.messages", l);
    }

    public String text(I18n i18n) {
        return bundle(getLocale()).getString(i18n.getKey());
    }

    public String format(I18n i18n, Object... args) {
        return new MessageFormat(text(i18n), getLocale()).format(args);
    }

    public StringBinding bind(I18n key) {
        return Bindings.createStringBinding(
                () -> text(key),
                locale
        );
    }

    public StringBinding bind(I18n key, Object... args) {
        return Bindings.createStringBinding(
                () -> format(key, args),
                locale
        );
    }
}
