package org.implab.gradle.common.exec.runtime;

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;
import org.implab.gradle.common.exec.model.CommandSpec;
import org.implab.gradle.common.exec.model.EnvironmentSpec;
import org.implab.gradle.common.exec.model.PipeSpec;

@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));
    }

}
