package com.atlassian.stash.internal.spring;

import java.util.Properties;
import org.springframework.util.PropertyPlaceholderHelper;

public class PlaceholderResolvingProperties extends Properties {

    private final PropertyPlaceholderHelper propertyPlaceholderHelper;
    private final PropertyPlaceholderHelper.PlaceholderResolver placeholderResolver;

    public PlaceholderResolvingProperties(final Properties defaults) {
        super(defaults);

        propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
        placeholderResolver = new PropertyPlaceholderHelper.PlaceholderResolver() {

            @Override
            public String resolvePlaceholder(String key) {
                return defaults.getProperty(key);
            }
        };
    }

    /**
     * Parses a property and returns the resolved value of the property.
     * @param key the property key
     * @return the result of resolving the property value's placeholders.
     */
    @Override
    public String getProperty(String key) {
        String value = super.getProperty(key);
        if (value != null) {
            value = propertyPlaceholderHelper.replacePlaceholders(value, placeholderResolver);
        }

        return value;
    }
}
