/*
 * Copyright © 2015 Stefan Niederhauser (nidin@gmx.ch)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package guru.nidi.graphviz.engine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import static guru.nidi.graphviz.engine.Format.SVG_STANDALONE;

final class GraphvizServer {
    private static final Logger LOG = LoggerFactory.getLogger(GraphvizServer.class);
    static final int PORT = 10234;

    private GraphvizServer() {
    }

    public static void start() throws IOException {
        final boolean windows = System.getProperty("os.name").contains("windows");
        final String executable = windows ? "java.exe" : "java";
        final Process process = new ProcessBuilder(System.getProperty("java.home") + "/bin/" + executable,
                "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())
                .inheritIO()
                .start();
        System.out.println(process.isAlive());
    }

    public static void main(String... args) throws IOException {
        LOG.info("starting graphviz server...");
        Graphviz.useEngine(new GraphvizV8Engine(), new GraphvizJdkEngine());
        LOG.info("started.");
        Graphviz.initEngine();
        LOG.info("inited.");
        try (final ServerSocket ss = new ServerSocket(PORT)) {
            while (true) {
                try (final Socket socket = ss.accept();
                     final Communicator com = new Communicator(socket.getInputStream(), socket.getOutputStream())) {
                    final int len = com.readLen();
                    if (len != 0) {
                        if (len == -1) {
                            break;
                        }
                        final String raw = com.readContent(len);
                        final int pos = raw.indexOf("@@@");
                        final Options options;
                        final String src;
                        if (pos < 0) {
                            options = Options.create().format(SVG_STANDALONE);
                            src = raw;
                        } else {
                            options = Options.fromJson(raw.substring(0, pos));
                            src = raw.substring(pos + 3);
                        }
                        try {
                            final String svg = Graphviz.fromString(src)
                                    .engine(options.engine).totalMemory(options.totalMemory)
                                    .render(options.format).toString();
                            com.writeStatus("ok");
                            com.writeContent(svg);
                        } catch (GraphvizException e) {
                            com.writeStatus("fail");
                            com.writeContent(e.getMessage());
                        }
                    }
                } catch (Exception e) {
                    LOG.warn("Problem in communication", e);
                }
            }
        }
        LOG.info("graphviz server stopped.");
    }

}
@@ -1609,32 +1609,74 @@
 s IOException %7B%0A
+        System.out.println(%22WWWWWWWWWW%22);%0A
         LOG.info
@@ -2364,19 +2364,17 @@
  String 
-raw
+s
  = com.r
@@ -2418,91 +2418,18 @@
     
-final int pos = raw.indexOf(%22@@@%22);%0A                        final Options options;%0A
+try %7B%0A    
     
@@ -2462,18 +2462,30 @@
 String s
-rc
+vg = render(s)
 ;%0A      
@@ -2506,22 +2506,34 @@
     
-if (pos %3C 0) %7B
+    com.writeStatus(%22ok%22);
 %0A   
@@ -2561,206 +2561,198 @@
     
-options = Options.create().format(SVG_STANDALONE);%0A                            src = raw;%0A                        %7D else %7B%0A                            options = Options.fromJson(raw.substring(0, pos
+com.writeContent(svg);%0A                        %7D catch (GraphvizException e) %7B%0A                            com.writeStatus(%22fail%22);%0A                            com.writeContent(e.getMessage(
 ));%0A
@@ -2779,46 +2779,10 @@
     
-  
-  src = raw.substring(pos + 3);%0A    
+%7D%0A
     
@@ -2811,35 +2811,45 @@
             
-        try
+%7D catch (Exception e)
  %7B%0A         
@@ -2863,59 +2863,48 @@
     
-        final String svg = Graphviz.fromString(src)
+LOG.warn(%22Problem in communication%22, e);
 %0A   
@@ -2908,32 +2908,34 @@
                 
+%7D%0A
                 
@@ -2928,24 +2928,28 @@
         
+  %7D%0A
         
   .engin
@@ -2944,348 +2944,318 @@
     
-  .engine(options.engine).totalMemory(options.totalMemory)
+%7D%0A        LOG.info(%22graphviz server stopped.%22);
 %0A    
+%7D%0A%0A
     
-                            .render(options.format).toString();%0A                            com.writeStatus(%22ok%22);%0A                            com.writeContent(svg);%0A                        %7D catch (GraphvizException e) %7B%0A                            com.writeStatus(%22fail%22)
+private static String render(String raw) %7B%0A        final int pos = raw.indexOf(%22@@@%22);%0A        final Options options;%0A        final String src;%0A        if (pos %3C 0) %7B%0A            options = Options.create().format(SVG_STANDALONE);%0A            src = raw
 ;%0A  
@@ -3252,32 +3252,41 @@
  = raw;%0A        
+%7D else %7B%0A
                 
@@ -3285,284 +3285,273 @@
     
-        com.writeContent(e.getMessage());%0A                        %7D%0A                    %7D%0A                %7D catch (Exception e) %7B%0A                    LOG.warn(%22Problem in communication%22, e);%0A                %7D%0A            %7D%0A        %7D%0A        LOG.info(%22graphviz server stopped.%22
+options = Options.fromJson(raw.substring(0, pos));%0A            src = raw.substring(pos + 3);%0A        %7D%0A        return Graphviz.fromString(src)%0A                .engine(options.engine).totalMemory(options.totalMemory)%0A                .render(options.format).toString(
 );%0A 

send options to GraphvizServer