package com.atlassian.bitbucket.test;

import com.atlassian.utils.process.ExternalProcess;
import com.atlassian.utils.process.ExternalProcessBuilder;
import com.atlassian.utils.process.StringProcessHandler;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class ProcessTestHelper {

    private static final Logger log = LoggerFactory.getLogger(ProcessTestHelper.class);
    private final File repositoryDirectory;
    private final Map<String, String> env;

    public ProcessTestHelper(File repositoryDirectory) {
        this(repositoryDirectory, Collections.emptyMap());
    }

    public ProcessTestHelper(File repositoryDirectory, Map<String, String> env) {
        this.repositoryDirectory = repositoryDirectory;
        this.env = env;
    }

    public ProcessTestHelper execute(String... parts) {
        execute(repositoryDirectory, env, parts);

        return this;
    }

    public static ProcessResult execute(File repositoryDirectory, String... parts) throws ProcessFailedException {
        return execute(repositoryDirectory, Collections.emptyMap(), parts);
    }

    public static ProcessResult execute(File repositoryDirectory, Map<String, String> env, String... parts) throws ProcessFailedException {
        List<String> command = Arrays.asList(parts);

        StringProcessHandler handler = new StringProcessHandler();
        ExternalProcess process = new ExternalProcessBuilder()
                .command(command, repositoryDirectory)
                .env(env)
                .handler(handler)
                .build();
        process.execute();
        if (log.isDebugEnabled()) {
            log.debug("Command: {}", process.getCommandLine());
            if (StringUtils.isNotBlank(handler.getOutput())) {
                log.debug("StdOut:\n{}", handler.getOutput());
            }
        }

        return ProcessResultFactory.createOrThrow(process, handler);
    }

    public ProcessTestHelper git(String... parts) {
        ImmutableList<String> gitParts = ImmutableList.<String>builder()
                .add(GitTestHelper.getGitPath())
                .add(parts)
                .build();
        execute(repositoryDirectory, env, gitParts.toArray(new String[gitParts.size()]));

        return this;
    }
}
