package org.implab.gradle.common.dsl;

import java.io.File;
import java.io.InputStream;
import java.util.Optional;
import java.util.function.Supplier;

import org.gradle.api.provider.Provider;
import org.gradle.util.Configurable;
import org.implab.gradle.common.exec.RedirectFrom;
import org.implab.gradle.common.utils.Closures;

import groovy.lang.Closure;

public class RedirectFromSpec implements Configurable<RedirectFromSpec> {
    private Supplier<RedirectFrom> streamRedirect;

    public boolean isRedirected() {
        return streamRedirect != null;
    }

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

    public void fromFile(File file) {
        streamRedirect = () -> RedirectFrom.file(file);
    }

    public void fromFile(Provider<File> fileProvider) {
        streamRedirect = fileProvider.map(RedirectFrom::file)::getOrNull;
    }

    public void fromStream(InputStream stream) {
        streamRedirect = () -> RedirectFrom.stream(stream);
    }

    public void fromStream(Provider<InputStream> streamProvider) {
        streamRedirect = streamProvider.map(RedirectFrom::stream)::getOrNull;
    }

    public void from(Object input) {
        if (input instanceof Provider<?> inputProvider) {
            streamRedirect = inputProvider.map(RedirectFrom::any)::get;
        } else {
            streamRedirect = () -> RedirectFrom.any(input);
        }
    }

    public void empty() {
        streamRedirect = () -> null;
    }

    @Override
    public RedirectFromSpec configure(Closure cl) {
        Closures.apply(cl, this);
        return this;
    }


}
