package de.siphalor.was.content.lang;

import de.siphalor.was.content.ContentManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

public class I18n extends ResourceBundle {
	public static final String DEFAULT = "en_us";

	private final Lang DEFAULT_LANG = new Lang(DEFAULT);

	private static final I18n INSTANCE = new I18n();

	public static I18n getInstance() {
		return INSTANCE;
	}

	@Nullable
	private Lang lang;

	public Lang getLang() {
		if (lang != null)
			return lang;
		return DEFAULT_LANG;
	}

	public void setLang(@NotNull String code, @NotNull ContentManager contentManager) {
		if (lang == null || !lang.getCode().equals(code)) {
			lang = new Lang(code);
			lang.load(contentManager);
		}
	}

	public void reload(@NotNull ContentManager contentManager) {
		DEFAULT_LANG.load(contentManager);
		if (lang != null) {
			lang.load(contentManager);
		}
	}

	@NotNull
	public String format(@NotNull String key, @Nullable Object... args) {
		return String.format(getString(key), args);
	}

	@Override
	@NotNull
	protected Object handleGetObject(@NotNull String key) {
		String val;
		if (lang != null) {
			val = lang.get(key);
			if (val == null) {
				val = DEFAULT_LANG.get(key);
			}
		} else {
			val = DEFAULT_LANG.get(key);
		}

		if (val == null) {
			return key;
		}
		return val;
	}

	@NotNull
	@Override
	public Enumeration<String> getKeys() {
		if (lang == null)
			return DEFAULT_LANG.getKeys();
		Set<String> keys = new HashSet<>(Collections.list(lang.getKeys()));
		keys.addAll(Collections.list(DEFAULT_LANG.getKeys()));
		return Collections.enumeration(keys);
	}
}
