package org.limine.snapper.processes;

import java.util.HashMap;
import java.util.Map;

public class MacroReplacer {

    public static final Map<String, String> MACROS = new HashMap<>();

    public static void parseMacro(String line) {
        String lineTrim = line.trim();
        if (lineTrim.startsWith("${") && line.contains("}=")) {
            int endOfKey = lineTrim.indexOf('}');
            String key = lineTrim.substring(2, endOfKey);
            String value = lineTrim.substring(endOfKey + 2);
            MACROS.put(key, value);
        }
    }

    public static String replaceMacros(String line) {
        if (line.trim().startsWith("#") || line.contains("}=")) {
            return line;
        }
        if (line.contains("${")) {
            for (Map.Entry<String, String> entry : MACROS.entrySet()) {
                String key = "${" + entry.getKey() + "}";
                String value = entry.getValue();
                line = line.replace(key, value);
            }
            if (line.contains("${")) {
                String errMessage = "Incorrect config: " + "No definition of macro found: " + line.replace("${", "\\${");
                Utility.exitWithError(errMessage);
            }
        }
        return line;
    }

}
