package org.arquillian.cube.docker.impl.requirement;

import org.arquillian.cube.docker.impl.util.CommandLineExecutor;
import org.arquillian.cube.spi.requirement.Requirement;
import org.arquillian.cube.spi.requirement.UnsatisfiedRequirementException;
import org.arquillian.spacelift.execution.ExecutionException;

public class DockerMachineRequirement implements Requirement<RequiresDockerMachine> {

    private static final String NEWLINE_PATTERN = "\r\n|\r|\n";
    private final CommandLineExecutor commandLineExecutor = new CommandLineExecutor();


    @Override
    public void check(RequiresDockerMachine context) throws UnsatisfiedRequirementException {
        String name = context.name();
        try {
            if (name != null && !name.isEmpty()) {
                String ip = commandLineExecutor.execCommand(new String[]{"docker-machine", "ip", name});
                if (ip == null || ip.isEmpty()) {
                    throw new UnsatisfiedRequirementException("Docker machine with name: ["+name+"] not found!");
                }
            } else {
                int machines = countLines(commandLineExecutor.execCommand(new String[]{"docker-machine", "ls"})) - 1;
                if (machines > 0) {
                    throw new UnsatisfiedRequirementException("No docker machine found!");
                }
            }
        } catch (ExecutionException e) {
            throw new UnsatisfiedRequirementException("Cannot execute docker-machine command.");
        }
    }


    private static int countLines(String s) {
        String[] lines = s.split(NEWLINE_PATTERN);
        return lines.length;
    }
}

@@ -47,16 +47,40 @@
 ement;%0A%0A
+import java.util.List;%0A%0A
 import o
@@ -422,72 +422,8 @@
  %7B%0A%0A
-    private static final String NEWLINE_PATTERN = %22%5Cr%5Cn%7C%5Cr%7C%5Cn%22;%0A
     
@@ -738,17 +738,29 @@
     
+List%3C
 String
- ip
+%3E machines
  = c
@@ -785,38 +785,32 @@
 .execCommand
-(new String%5B%5D%7B
+AsArray(
 %22docker-mach
@@ -820,66 +820,110 @@
 %22, %22
-ip
+ls%22, %22--filter
 %22, 
+%22
 name
-%7D);%0A                if (ip == null %7C%7C ip.isEmpty(
+=%22 + name, %22--format%22, %22%7B%7B.Name%7D%7D%22);%0A                if (!machines.contains(name
 )) %7B
@@ -1092,19 +1092,28 @@
         
-int
+List%3CString%3E
  machine
@@ -1116,27 +1116,16 @@
 hines = 
-countLines(
 commandL
@@ -1151,22 +1151,16 @@
 mand
-(new String%5B%5D%7B
+AsArray(
 %22doc
@@ -1181,15 +1181,34 @@
 %22ls%22
-%7D)) - 1
+, %22--format%22, %22%7B%7B.Name%7D%7D%22)
 ;%0A  
@@ -1233,16 +1233,23 @@
 machines
+.size()
  %3E 0) %7B%0A
@@ -1530,139 +1530,6 @@
  %7D%0A%0A
-%0A    private static int countLines(String s) %7B%0A        String%5B%5D lines = s.split(NEWLINE_PATTERN);%0A        return lines.length;%0A    %7D%0A
 %7D%0A

Improve Docker Machine Requirement (#430)