package org.jboss.installer.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Exposes selected build properties defined in the pom
 */
public class BuildProperties {

    private final String propertyFileName;
    private static final BuildProperties INSTANCE = new BuildProperties();
    public static final String EAP_VERSION = BuildProperties.INSTANCE.getProperty("eap.release.version");
    public static final String PROSPERO_INSTALLATION_PROFILE = BuildProperties.INSTANCE.getProperty("prospero.eap.profile");
    public static final String EAP_FEATURE_PACK_LOCATION = BuildProperties.INSTANCE.getProperty("prospero.eap.fpl");
    public static final String MYFACES_FEATURE_PACK_GA = BuildProperties.INSTANCE.getProperty("myfaces.feature-pack.ga");
    public static final boolean IS_WILDFLY_INSTALLATION = PROSPERO_INSTALLATION_PROFILE.equals("wildfly-ee");
    public static final Map<String, URL> DEFAULT_PRODUCT_REPOSITORIES;

    static {
        final HashMap<String, URL> repos = new HashMap<>();
        final String combinedRepositories = BuildProperties.INSTANCE.getProperty("product.repositories");
        for (String repoDef : combinedRepositories.split(",")) {
            String[] v = repoDef.split("::");
            try {
                repos.put(v[0], URI.create(v[1]).toURL());
            } catch (MalformedURLException e) {
                throw new RuntimeException("Unable to parse the product repository: " + v[1], e);
            }
        }
        DEFAULT_PRODUCT_REPOSITORIES = Collections.unmodifiableMap(repos);
    }

    private BuildProperties() {
        this.propertyFileName = "pom_extracted.properties";
    }

    // keeping package-protected to enable uit testing
    BuildProperties(String propertyFileName) {
        this.propertyFileName = propertyFileName;
    }

    String getProperty(String propertyName) {
        Properties properties = new Properties();
        try (final InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream(propertyFileName)) {
            properties.load(inputStream);
            if (!properties.containsKey(propertyName)) {
                throw new InstallerRuntimeException("Unable to determine required version from properties.");
            }
        } catch (IOException e) {
            throw new InstallerRuntimeException("Unable to determine required version from properties.", e);
        }

        return properties.getProperty(propertyName);
    }
}
