package alda.integrationtests;

import alda.AldaClient;
import alda.AldaServerOptions;
import alda.testutils.AldaServerInfo;
import alda.testutils.TestEnvironment;
import alda.testutils.TestEnvironmentStatus;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.junit.Assert.*;

/*
 * The test environment is created before, and teared down after,
 * *all* the tests, by the class Alda.testutils.AldaJunitRunListener
 */
public class AldaClientTest {

    private final ByteArrayOutputStream stdOutContent = new ByteArrayOutputStream();

    @Test
    public void listProcessesOutput() throws Exception {
        /*
        while(TestEnvironment.getStatus() != TestEnvironmentStatus.STARTED) {
          System.err.println("Awaiting test environment to start...");
          Thread.sleep(1500);
        }
        */

        // Redirect StdOut
        PrintStream oldStdOut = System.out;
        System.setOut(new PrintStream(stdOutContent));
        try {
            AldaServerOptions serverOpts = new AldaServerOptions();
            serverOpts.timeout = 30;
            AldaClient.listProcesses(serverOpts);

            Map<Integer, Integer> serverPortsFound = new HashMap<>();
            Pattern serverPortPattern = Pattern.compile("\\[(.*?)\\]");
            Pattern serverBackendPortPattern = Pattern.compile("backend port\\:(.*?)\\)");

            String[] stdOutLines = stdOutContent.toString().split("\n");
            for (String line : stdOutLines){
                // Format: [27716] Server up (2/2 workers available, backend port: 39998)
                if (line.contains("Server up")){
                    Matcher sp = serverPortPattern.matcher(line);
                    if (sp.find()){
                        int srvPort = Integer.parseInt(cleanAnsiEscapes(sp.group(1)));
                        int numberOfWorkers = 0;

                        Matcher sbp = serverBackendPortPattern.matcher(line);
                        if (sbp.find()){
                            int srvBackendPort = Integer.parseInt(sbp.group(1).trim());
                            numberOfWorkers = parseOutputForNumberOfWorkersOnBackendPort(stdOutLines, srvBackendPort);
                        }

                        serverPortsFound.put(srvPort, numberOfWorkers);
                    }
                }
            }

            for(AldaServerInfo server: TestEnvironment.getRunningServers()) {
                assertTrue("Running server not listed.", serverPortsFound.containsKey(server.getPort()) );
                assertEquals("Number of workers for server don't match.", server.getNumberOfWorkers(), serverPortsFound.get(server.getPort()).intValue() );
            }

        } finally {
            // Reset StdOut
            System.setOut(oldStdOut);
            System.out.println(stdOutContent);
        }

    }

    private String cleanAnsiEscapes(String string) {
        return string.replaceAll("\u001B\\[[;\\d]*m", "");
    }

    private int parseOutputForNumberOfWorkersOnBackendPort(String[] lines, int srv_backend_port) {
        int workersFound = 0;
        for (String line : lines) {
            // Format: [46672] Worker (pid: 6368)
            if (line.contains("["+srv_backend_port+"] Worker")) {
                workersFound++;
            }
        }
        return workersFound;
    }

    @Test
    public void testCheckForExistingServer() throws Exception {
        for(AldaServerInfo server: TestEnvironment.getRunningServers()) {
            assertTrue("Alda Client didn't detect running server.", AldaClient.checkForExistingServer(server.getPort()) );
        }
        assertFalse("Alda Client detects running Server on a port where there should be none. ",AldaClient.checkForExistingServer(TestEnvironment.NO_SERVER_RUNNING_PORT));
    }

}

@@ -829,220 +829,8 @@
 n %7B%0A
-        /*%0A        while(TestEnvironment.getStatus() != TestEnvironmentStatus.STARTED) %7B%0A          System.err.println(%22Awaiting test environment to start...%22);%0A          Thread.sleep(1500);%0A        %7D%0A        */%0A%0A
     
@@ -844,32 +844,32 @@
 Redirect StdOut%0A
+
         PrintStr
@@ -1029,24 +1029,63 @@
 rOptions();%0A
+            serverOpts.noColor = true;%0A
             
@@ -1808,33 +1808,16 @@
 arseInt(
-cleanAnsiEscapes(
 sp.group
@@ -1820,17 +1820,16 @@
 roup(1))
-)
 ;%0A      
@@ -2863,127 +2863,8 @@
  %7D%0A%0A
-    private String cleanAnsiEscapes(String string) %7B%0A        return string.replaceAll(%22%5Cu001B%5C%5C%5B%5B;%5C%5Cd%5D*m%22, %22%22);%0A    %7D%0A%0A
     

use noColor option, no longer have to strip out ANSI color codes