/*
 * Copyright 2014 Guidewire Software, Inc.
 */

package editor.util.transform.java;


import com.sun.source.tree.CompilationUnitTree;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.api.JavacTool;
import editor.util.transform.java.visitor.GosuVisitor;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;

public class GosuVisitorTestUtil {

  public String transform(String jsrc) throws IOException {
    String src = readFile(jsrc);
    if (src == null) {
      return null;
    }

    JavaCompiler compiler = JavacTool.create();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    ArrayList<JavaStringObject> javaStringObjects = new ArrayList<>();
    javaStringObjects.add(new JavaStringObject(src));
    Iterable<? extends JavaFileObject> compilationUnits = javaStringObjects;
    StringWriter errors = new StringWriter();
    JavaCompiler.CompilationTask task = compiler.getTask(errors, fileManager, null, null, null, compilationUnits);
    JavacTaskImpl javacTask = (JavacTaskImpl) task;
    String output = "";
    Iterable<? extends CompilationUnitTree> trees = javacTask.parse();
    if (errors.toString().isEmpty()) {
      GosuVisitor visitor = new GosuVisitor(4);
      for (CompilationUnitTree tree : trees) {
        tree.accept(visitor, null);
      }
      fileManager.close();
      output = visitor.getOutput().toString();
    }
    return output;
  }

  public String readFile(String path) throws IOException {
    StringBuilder src = new StringBuilder();
    path = Thread.currentThread().getContextClassLoader().getResource(path).getPath();
    Charset charset = Charset.forName("UTF8");
    try(BufferedReader reader = Files.newBufferedReader(Paths.get(path), charset)) {
      String line = null;
      while ((line = reader.readLine()) != null) {
        src.append(line).append("\n");
      }
    }
    return src.toString();
  }
}

@@ -404,16 +404,94 @@
 a.io.*;%0A
+import java.net.URI;%0Aimport java.net.URISyntaxException;%0Aimport java.net.URL;%0A
 import j
@@ -685,32 +685,34 @@
 rows IOException
+%0A 
  %7B%0A    String sr
@@ -1769,19 +1769,21 @@
 xception
+%0A 
  %7B%0A
-
     Stri
@@ -1823,20 +1823,55 @@
 ();%0A    
-path
+URL url = null;%0A    try%0A    %7B%0A      url
  = Threa
@@ -1928,72 +1928,124 @@
 rce(
+ 
 path
+ 
 ).
-getPath();%0A    Charset charset = Charset.forName(%22UTF8%22
+toURI().toURL();%0A    %7D%0A    catch( URISyntaxException e )%0A    %7B%0A      throw new RuntimeException( e 
 );%0A
+    %7D%0A
     
@@ -2076,17 +2076,12 @@
 r = 
-Files.
 new
+ 
 Buff
@@ -2095,32 +2095,47 @@
 der(
-Paths.get(path), charset
+new InputStreamReader(url.openStream())
 )) %7B
@@ -2152,23 +2152,16 @@
 ing line
- = null
 ;%0A      

Fix test on Win