package com.atlassian.stash.internal.scm.git.submodule;

import com.atlassian.stash.internal.scm.git.command.config.ConfigOutputHandler;
import com.atlassian.stash.internal.scm.git.command.config.ConfigSection;
import com.atlassian.bitbucket.scm.CommandOutputHandler;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;

import java.util.Collection;
import java.util.Map;

/**
 * Parses the output of the <a href="http://www.kernel.org/pub/software/scm/git/docs/gitmodules.html">Git submodule</a> file,
 * which is in the following format.
 * <p>
 * <pre>
 * [submodule "ignore_me"]
 *     path = rep_1
 *     url = ssh://git@localhost:7999/PROJECT_1/rep_1.git
 * </pre>
 *
 * @since 2.3
 */
class SubmoduleOutputHandler extends ConfigOutputHandler implements CommandOutputHandler<Map<String, String>> {

    @Override
    public Map<String, String> getOutput() {
        Map<String, String> modules = Maps.newHashMap();
        for (ConfigSection section : getSections()) {
            modules.put(getSingleString(section, "path"), getSingleString(section, "url"));
        }
        return modules;
    }

    private String getSingleString(ConfigSection section, String key) {
        Collection<String> values = section.getEntries().get(key);
        if (values.isEmpty()) {
            throw new IllegalStateException("Missing configuration " + key + " for module section: " + section.getSubsection());
        }
        return Iterables.getFirst(values, null);
    }
}
