package com.suse.salt.netapi.examples;

import com.suse.salt.netapi.calls.SaltSSHConfig;
import com.suse.salt.netapi.calls.modules.Grains;
import com.suse.salt.netapi.calls.modules.Test;
import com.suse.salt.netapi.client.SaltClient;
import com.suse.salt.netapi.datatypes.target.Glob;
import com.suse.salt.netapi.datatypes.target.Target;
import com.suse.salt.netapi.exception.SaltException;
import com.suse.salt.netapi.results.Result;
import com.suse.salt.netapi.results.SSHResult;

import java.net.URI;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Example code calling salt modules via ssh.
 */
public class SaltSSH {

    private static final String SALT_API_URL = "http://localhost:8000";

    public static void main(String[] args) throws SaltException {
        // Init the client
        SaltClient client = new SaltClient(URI.create(SALT_API_URL));

        // Setup the configuration for Salt SSH (use defaults)
        SaltSSHConfig sshConfig = new SaltSSHConfig.Builder().build();

        // Ping all minions using a glob matcher
        Target<String> globTarget = new Glob("*");
        Map<String, Result<SSHResult<Boolean>>> minionResults =
                Test.ping().callSyncSSH(client, globTarget, sshConfig);

        System.out.println("--> Ping results:\n");
        minionResults.forEach((minion, result) -> {
            System.out.println(minion + " -> " + result.fold(
                    error -> "Error: " + error.toString(),
                    res -> res.getReturn().orElse(false)
            ));
        });

        // Get grains from all minions
        Map<String, Result<SSHResult<Map<String, Object>>>> grainResults =
                Grains.items(false).callSyncSSH(client, globTarget, sshConfig);

        grainResults.forEach((minion, grains) -> {
            System.out.println("\n--> Listing grains for '" + minion + "':\n");
            String grainsOutput = grains.fold(
                    error -> "Error: " + error.toString(),
                    grainsMap -> {
                            grainsMap.getReturn().ifPresent(gmap -> gmap.entrySet().stream()
                                    .map(e -> e.getKey() + ": " + e.getValue())
                                    .collect(Collectors.joining("\n")));
                            return "Minion did not return: " + minion;
                    }
            );
            System.out.println(grainsOutput);
        });
    }
}

@@ -2014,25 +2014,45 @@
 rainsMap -%3E 
-%7B
+grainsMap.getReturn()
 %0A           
@@ -2072,52 +2072,19 @@
     
-grainsMap.getReturn().ifPresent(gmap
+.map(g
  -%3E g
-map
 .ent
@@ -2251,17 +2251,16 @@
 (%22%5Cn%22)))
-;
 %0A       
@@ -2284,15 +2284,16 @@
     
-return 
+.orElse(
 %22Min
@@ -2326,31 +2326,9 @@
 nion
-;%0A                    %7D
+)
 %0A   

Use map(...).orElse() to return a default string