/**
 * Copyright 2014 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.netflix.config;

import org.apache.commons.configuration.AbstractConfiguration;

public class ConfigurationBackedDynamicPropertySupportImpl implements DynamicPropertySupport {

    private final AbstractConfiguration config;
        
    public ConfigurationBackedDynamicPropertySupportImpl(AbstractConfiguration config) {
        if (config == null) {
            throw new NullPointerException("config is null");
        }
        this.config = config;
    }
    
    @Override
    public String getString(String key) {
        try {
            String values[] = config.getStringArray(key);
            if (values == null) {
                return null;
            }
            if (values.length == 0) {
                return config.getString(key);
            } else if (values.length == 1) {
                return values[0];
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                sb.append(values[i]);
                if (i != values.length - 1) {
                    sb.append(",");
                }
            }
            return sb.toString();
        } catch (Exception e) {
            Object v = config.getProperty(key);
            if (v != null) {
                return String.valueOf(v);
            } else {
                return null;
            }
        }
    }

    @Override
    public void addConfigurationListener(PropertyListener expandedConfigListener) {
        ExpandedConfigurationListenerAdapter nl = new ExpandedConfigurationListenerAdapter(expandedConfigListener);
        config.addConfigurationListener(nl);    
    }
    
    public final AbstractConfiguration getConfiguration() {
        return config;
    }
}
