/* © SRSoftware 2025 */
package de.srsoftware.umbrella.translations;

import static de.srsoftware.umbrella.core.constants.Field.BASE_URL;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.missingField;
import static java.lang.System.Logger.Level.WARNING;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.configuration.Configuration;
import de.srsoftware.tools.Path;
import de.srsoftware.tools.PathHandler;
import de.srsoftware.umbrella.core.ModuleRegistry;
import de.srsoftware.umbrella.core.api.Translator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.json.JSONObject;

public class Translations extends PathHandler implements Translator {
	private static final System.Logger LOG = System.getLogger("Translations");
	private final String baseUrl;

	private HashMap<String, JSONObject> translations = new HashMap<>();

	public Translations(Configuration config) {
		ModuleRegistry.add(this);
		Optional<String> baseUrl = config.get(BASE_URL);
		if (baseUrl.isEmpty()) throw missingField(BASE_URL);
		this.baseUrl = baseUrl.get();
	}

	@Override
	public boolean doGet(Path path, HttpExchange ex) throws IOException {
		allowOrigin(ex,"*");
		if (path.empty())return sendContent(ex,501,"Language missing");
		var lang = path.pop();
		return sendContent(ex,getTranslations(lang));
	}

	private JSONObject getTranslations(String lang) throws IOException {
		var result = translations.get(lang);
		if (result == null) translations.put(lang,result = loadTranslations(lang));
		return result;
	}

	private JSONObject loadTranslations(String lang) throws IOException {
		var filename = lang + ".json";
		URL url = getClass().getClassLoader().getResource(filename);
		if (url == null) return new JSONObject();
		var bos = new ByteArrayOutputStream();
		var conn = url.openConnection();
		try (var stream = conn.getInputStream()){
			stream.transferTo(bos);
			return new JSONObject(bos.toString(UTF_8));
		} catch (Exception e) {
			LOG.log(WARNING,"Failed to load {0}",url);
			return new JSONObject();
		}
	}

	@Override
	public String translate(String language, String text, Map<String,String> fills) {
		try {
			var translations = getTranslations(language);
			var keys = text.split("\\.");
			Object current = translations;
			for (var key : keys){
				if (current instanceof JSONObject json && json.has(key)) {
					current = json.get(key);
				} else current = null;
			}
			var translated = current instanceof String translation ? translation : text;
			if (fills != null) for (var entry : fills.entrySet()) {
				translated = translated.replaceAll("\\{"+entry.getKey()+"}",entry.getValue());
			}
			return translated.replaceAll("\\{base_url}",baseUrl);
		} catch (IOException e) {
			return text;
		}
	}
}
