package com.atlassian.bitbucket.mesh.config;

import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;

import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.Map;

class DefaultGitProcessConfig implements GitProcessConfig {

    private final Settings settings;

    DefaultGitProcessConfig(@Nonnull Environment environment) {
        settings = Binder.get(environment).bindOrCreate("git.process", Settings.class);
    }

    @Nonnull
    @Override
    public Map<String, String> getConfiguration() {
        return settings.configuration;
    }

    @Nonnull
    @Override
    public Map<String, String> getEnvironment() {
        return settings.environment;
    }

    private static class Settings {

        final Map<String, String> configuration;
        final Map<String, String> environment;

        @ConstructorBinding
        public Settings(Map<String, String> configuration, Map<String, String> environment) {
            //If either property isn't set, bindOrCreate will pass null when constructing the Settings
            //instance, so we default to empty maps in that case.
            this.configuration = defaultOrWrap(configuration);
            this.environment = defaultOrWrap(environment);
        }

        private static Map<String, String> defaultOrWrap(Map<String, String> map) {
            return map == null ? Collections.emptyMap() : Collections.unmodifiableMap(map);
        }
    }
}
