package cn.ibizlab.codegen.templating;


import java.util.Locale;
import java.util.ServiceLoader;

public class TemplatingEngineLoader {
    private TemplatingEngineLoader() {
        throw new IllegalStateException("Utility class");
    }

    @SuppressWarnings("java:S112") // ignore java:S112 as generic RuntimeException is acceptable here
    public static TemplatingEngineAdapter byIdentifier(String id) {
        ServiceLoader<TemplatingEngineAdapter> loader = ServiceLoader.load(TemplatingEngineAdapter.class, TemplatingEngineLoader.class.getClassLoader());

        StringBuilder sb = new StringBuilder();
        for (TemplatingEngineAdapter templatingEngineAdapter : loader) {
            if (id.equals(templatingEngineAdapter.getIdentifier())) {
                return templatingEngineAdapter;
            }
            sb.append(templatingEngineAdapter.getIdentifier()).append("\n");
        }

        try {
            // Attempt to load skipping SPI
            return (TemplatingEngineAdapter) Class.forName(id).getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(String.format(Locale.ROOT, "Couldn't load template engine adapter %s. Available options: %n%s", id, sb), e);
        }
    }
}
