package org.implab.gradle.common.exec;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;

@NonNullByDefault
class EchoExecBuilder extends AbstractExecBuilder<CommandSpec> {

    private final boolean echoToStderr;

    public EchoExecBuilder(CommandSpec command, boolean echoToStderr) {
        super(command);
        this.echoToStderr = echoToStderr;
    }

    @Override
    protected CompletableFuture<Integer> startInternal(
            CommandSpec command,
            EnvironmentSpec environment,
            PipeSpec redirect) throws IOException {

        var outputRedirect = echoToStderr ? redirect.stderr() : redirect.stdout();

        return outputRedirect
                .map(to -> {
                    var bytes = String
                            .format(
                                    "exec: %s",
                                    command.commandLine().stream().collect(Collectors.joining(" ")))
                            .getBytes(StandardCharsets.UTF_8);

                    return to.redirect(new ByteArrayInputStream(bytes))
                            .thenApply((x) -> 0);
                })
                .orElse(CompletableFuture.completedFuture(0));
    }

}
