package de.siphalor.was.content.lang;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;

public class Lang {
	private final String code;
	private final Properties properties = new Properties();

	public Lang(@NotNull String code) {
		this.code = code;
	}

	@NotNull
	public String getCode() {
		return code;
	}

	public void load(@NotNull ContentManager contentManager) {
		properties.clear();
		contentManager.getAllOfResource("lang/" + code + ".properties").forEachOrdered(resource -> {
			InputStream inputStream = resource.getInputStream();
			if (inputStream != null) {
				try {
					properties.load(inputStream);
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});

		if (properties.isEmpty()) {
			Util.LOGGER.log(Level.SEVERE, "Failed to load lang file for " + code);
		}
	}

	@Nullable
	public String get(@NotNull String key) {
		return (String) properties.get(key);
	}

	@NotNull
	public Enumeration<String> getKeys() {
		// This is really ugly but we know™ that the keys will always be strings
		//noinspection unchecked
		return (Enumeration<String>)(Object) properties.keys();
	}
}
