/* © SRSoftware 2025 */
package de.srsoftware.umbrella.core.model;

import static de.srsoftware.tools.Optionals.*;

import de.srsoftware.umbrella.core.ModuleRegistry;
import java.util.HashMap;
import java.util.Map;

public class Translatable {
	protected final String message;
	private final Map<String, Object> fills;
	private final HashMap<String,String> translated = new HashMap<>();

	public Translatable(String message, Map<String,Object> fills){
		this.fills   = fills;
		this.message = message;
	}

	public static Map<String,Object> argMap(Object ... args){
		var map = new HashMap<String,Object>();
		int i = 0;
		while (i+1<args.length){
			map.put(args[i].toString(),args[i+1]);
			i+=2;
		}
		return map;
	}

	@Override
	public String toString() {
		return translate(null);
	}

	public static Translatable t(String message, Object ... args){
		return t(message,argMap(args));
	}

	public static Translatable t(String message, Map<String, Object> args){
		return new Translatable(message,args);
	}

	public String translate(String language){
		var translation = language == null ? null : translated.get(language);
		if (translation == null){
			var translatedFills = new HashMap<String,String>();
			if (fills != null) {
				for (var entry : fills.entrySet()) {
					var o = entry.getValue();
					var val = switch (o) {
						case Translatable tr -> tr.translate(language);
						case String s -> s;
						default -> o.toString();
					};
					translatedFills.put(entry.getKey(), val);
				}
			}
			translation = ModuleRegistry.translator().translate(language,message,translatedFills);
			if (allSet(language, translation)) translated.put(language,translation);
		}
		return translation;
	}
}
