package org.implab.gradle.common.exec;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

/**
 * RedirectSpec
 */
public interface RedirectTo {
    CompletableFuture<Void> redirect(InputStream from);

    public static RedirectTo consumer(final Consumer<String> consumer) {

        return (src) -> CompletableFuture.runAsync(() -> {
            try (Scanner sc = new Scanner(src)) {
                while (sc.hasNextLine()) {
                    consumer.accept(sc.nextLine());
                }
            }
        });
    }

    public static RedirectTo file(final File file) {
        return src -> CompletableFuture.runAsync(() -> {
            try (OutputStream out = new FileOutputStream(file)) {
                src.transferTo(out);
            } catch (Exception e) {
                // silence!
            }
        });
    }

    public static RedirectTo stream(final OutputStream dest) {
        return src -> CompletableFuture.runAsync(() -> {
            try (dest; src) {
                src.transferTo(dest);
            } catch (Exception e) {
                // silence!
            }
        });
    }
}