package org.implab.gradle.common.dsl;

import java.io.File;
import java.io.OutputStream;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.gradle.api.provider.Provider;
import org.implab.gradle.common.exec.RedirectTo;

@NonNullByDefault
public class RedirectToSpec {
    private Supplier<RedirectTo> streamRedirect;
    
    public boolean isRedirected() {
        return getRedirection().isPresent();
    }

    public Optional<RedirectTo> getRedirection() {
        return streamRedirect != null ? Optional.ofNullable(streamRedirect.get()) : Optional.empty();
    }

    public @Nullable RedirectTo getRedirectionOrNull() {
        return streamRedirect != null ? streamRedirect.get() : null;
    }

    public void toFile(File file) {
        this.streamRedirect = () -> RedirectTo.file(file);
    }

    public void toFile(Provider<File> fileProvider) {
        this.streamRedirect = fileProvider.map(RedirectTo::file)::getOrNull;
    }

    public void toStream(OutputStream stream) {
        this.streamRedirect = () -> RedirectTo.stream(stream);
    }

    public void toStream(Provider<OutputStream> streamProvider) {
        this.streamRedirect = streamProvider.map(RedirectTo::stream)::getOrNull;
    }

    public void to(Object output) {
        if (output instanceof Provider<?> outputProvider) {
            this.streamRedirect = outputProvider.map(RedirectTo::any)::get;
        } else {
            this.streamRedirect = () -> RedirectTo.any(output);
        }
    }

    public void consume(Consumer<String> consumer) {
        this.streamRedirect = () -> RedirectTo.consumer(consumer);
    }
}
