package org.adrianvictor.lib.reflection;

public class ImplementationRegistry {

    private final String classSuffix;

    public ImplementationRegistry(String classSuffix) {
        this.classSuffix = classSuffix;
    }

    public <T> T getInstance(Class<T> apiClass, String target, String replacement) {
        String implName =
                apiClass.getName()
                        .replace(
                                target,
                                replacement + classSuffix + "."
                        );

        try {
            Class<?> implClass = Class.forName(implName);

            return apiClass.cast(
                    implClass.getDeclaredConstructor().newInstance()
            );
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException(
                    "Cannot load " + implName,
                    e
            );
        }
    }

    public <T> T getInstance(Class<T> apiClass) {
        return getInstance(apiClass, "org.adrianvictor.lib", "org.adrianvictor.lib.impl.");
    }
}
