package org.implab.gradle.common.exec;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

class EchoExecBuilder extends ExecBuilder {

    private final boolean echoToStderr;

    public EchoExecBuilder(boolean echoToStderr) {
        this.echoToStderr = echoToStderr;
    }

    @Override
    protected CompletableFuture<Integer> startInternal(Map<String, String> environment, File directory,
            List<String> commandLine, Optional<RedirectFrom> stdinRedirect, Optional<RedirectTo> stdoutRedirect,
            Optional<RedirectTo> stderrRedirect) throws IOException {
        var outputRedirect = echoToStderr ? stderrRedirect : stdoutRedirect;

        return outputRedirect.map(to -> {
            var bytes = String.format("exec: %s", commandLine).getBytes(StandardCharsets.UTF_8);
            return to.redirect(new ByteArrayInputStream(bytes)).thenApply((x) -> 0);
        }).orElse(CompletableFuture.completedFuture(0));
    }

}
