package org.implab.gradle.common.dsl;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.implab.gradle.common.exec.Executor;
import org.implab.gradle.common.exec.RedirectFrom;
import org.implab.gradle.common.exec.RedirectTo;

public class ProcessSpec {
    private RedirectFrom inputRedirect;

    private RedirectTo outputRedirect;

    private RedirectTo errorRedirect;

    private List<String> command = new ArrayList<>();

    private File directory;

    public ProcessSpec command(String... args) {
        command = new ArrayList<>();
        args(args);
        return this;
    }

    public ProcessSpec directory(File workingDir) {
        directory = workingDir;
        return this;
    }

    public ProcessSpec command(Collection<String> args) {
        command = new ArrayList<>();
        args(args);
        return this;
    }

    public ProcessSpec args(String... args) {
        for (String arg : args)
            command.add(arg);
        return this;
    }

    public ProcessSpec args(Collection<String> args) {
        command.addAll(args);
        return this;
    }

    public ProcessSpec stderr(RedirectTo to) {
        errorRedirect = to;
        return this;
    }

    public ProcessSpec stdin(RedirectFrom from) {
        inputRedirect = from;
        return this;
    }

    public ProcessSpec stdout(RedirectTo to) {
        outputRedirect = to;
        return this;
    }

    public void accept(Executor executor) {
        command.forEach(executor::argument);
        executor.directory(directory);
        if (inputRedirect != null)
            executor.stdin(inputRedirect);
        if (outputRedirect != null)
            executor.stdout(outputRedirect);
        if (errorRedirect != null)
            executor.stderr(errorRedirect);
    }


}
