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;

/**
 * A class for holding a language's data
 */
public class Lang {
	/**
	 * The language's data
	 */
	private final String code;
	/**
	 * The internally used properties file
	 */
	private final Properties properties = new Properties();

	/**
	 * Constructs a new language by its identification code.
	 * @param code The identifying code
	 */
	public Lang(@NotNull String code) {
		this.code = code;
	}

	/**
	 * Gets the language's code.
	 * @return The identifying code for this language
	 */
	@NotNull
	public String getCode() {
		return code;
	}

	/**
	 * Loads the language's data using the given content manager.
	 * @param contentManager The content manager to use
	 * @return Returns whether the load was successful
	 */
	public boolean 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);
			return false;
		}
		return true;
	}

	/**
	 * Gets the translation string
	 * @param key The key for the translation
	 * @return Returns the translation data
	 */
	@Nullable
	public String get(@NotNull String key) {
		return (String) properties.get(key);
	}

	/**
	 * Gets all of the translation keys
	 * @return Returns all of the translation keys
	 */
	@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();
	}
}
