package org.implab.gradle.common.dsl;

import java.util.HashMap;
import java.util.Map;

import org.gradle.api.Action;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.provider.MapProperty;
import org.implab.gradle.common.utils.Closures;
import org.implab.gradle.common.utils.Values;

import groovy.lang.Closure;

/**
 * Configuration properties of the execution shell. This object specifies a
 * working directory and environment variables for the processes started within
 * this shell.
 */
public interface EnvironmentSpec {

    /** Working directory */
    DirectoryProperty getWorkingDirectory();

    /** Environment variables */
    MapProperty<String, String> getEnvironment();

    /**
     * Configures the environment variable using the specified action. The
     * action is called when the value is calculated;
     */
    default void env(Action<Map<String, Object>> configure) {
        var provider = getEnvironment()
                .orElse(Map.of())
                .map((base) -> {
                    var props = new HashMap<String, Object>(base);

                    configure.execute(props);

                    return Values.mapValues(props, Values::toString);
                });

        getEnvironment().set(provider);
    }

    default void env(Closure<?> configure) {
        env(Closures.action(configure));
    }
}
