package kg.apc.emulators;

import kg.apc.jmeter.DirectoryAnchor;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.gui.tree.JMeterTreeListener;
import org.apache.jmeter.gui.tree.JMeterTreeModel;
import org.apache.jmeter.threads.*;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Locale;

public abstract class TestJMeterUtils {

    public static void createJmeterEnv() {
        File propsFile = null;
        try {
            propsFile = File.createTempFile("jmeter-plugins", ".properties");
            propsFile.deleteOnExit();
        } catch (IOException ex) {
            ex.printStackTrace(System.err);
        }

        assert propsFile != null;
        JMeterUtils.loadJMeterProperties(propsFile.getAbsolutePath());
        JMeterUtils.setJMeterHome(getTempDir());
        JMeterUtils.setLocale(new Locale("ignoreResources"));

        JMeterTreeModel jMeterTreeModel = new JMeterTreeModel();
        JMeterTreeListener jMeterTreeListener = new JMeterTreeListener();
        jMeterTreeListener.setModel(jMeterTreeModel);
        JMeterContextService.getContext().setVariables(new JMeterVariables());
        StandardJMeterEngine engine = new EmulatorJmeterEngine();
        JMeterThreadMonitor monitor = new EmulatorThreadMonitor();
        JMeterContextService.getContext().setEngine(engine);
        HashTree hashtree = new HashTree();
        hashtree.add(new LoopController());
        JMeterThread thread = new JMeterThread(hashtree, monitor, null);
        thread.setThreadName("test thread");
        JMeterContextService.getContext().setThread(thread);
        ThreadGroup threadGroup = new org.apache.jmeter.threads.ThreadGroup();
        threadGroup.setName("test thread group");
        JMeterContextService.getContext().setThreadGroup(threadGroup);
        JMeterUtils.setProperty("sample_variables", "TEST1,TEST2,TEST3"); // for Flexible File Writer Test
        JMeterUtils.setProperty("saveservice_properties", "/ss.props");
        JMeterUtils.setProperty("upgrade_properties", "/ss.props");

        File dst = new File(JMeterUtils.getJMeterHome() + "/ss.props");
        InputStream src = DirectoryAnchor.class.getResourceAsStream("/kg/apc/jmeter/bin/saveservice.properties");
        try {
            Files.copy(src, dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("Failed to copy file " + src + " to " + dst, e);
        }
    }

    public static String getTempDir() {
        Path f = null;
        try {
            f = Files.createTempDirectory("jpgc/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert f != null;
        return f.toString();
    }

    public static String getTestData(int i) {
        return RandomStringUtils.randomAlphanumeric(i);
    }


    public static String fixWinPath(String path) {
        String ret = path;
        //test if win os
        boolean isWinOs = System.getProperty("os.name").toLowerCase().contains("win");

        //fix only files in "document and settings", for computer with no admin / C: drive access...
        if (isWinOs) {
            ret = ret.replace("Documents%20and%20Settings", "DOCUME~1");
            ret = ret.replace("Local%20Settings", "LOCALS~1");
            ret = ret.replace("Application%20Data", "APPLIC~1");
        }

        return ret;
    }

    public static String convertStreamToString(InputStream is)
            throws IOException {
        /*
         * To convert the InputStream to String we use the Reader.read(char[]
         * buffer) method. We iterate until the Reader return -1 which means
         * there's no more data to read. We use the StringWriter class to
         * produce the string.
         */
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }
}

@@ -727,158 +727,328 @@
     
-File propsFile = null;%0A        try %7B%0A            propsFile = File.createTempFile(%22jmeter-plugins%22, %22.properties%22);%0A            propsFile.deleteOnExit(
+JMeterUtils.setJMeterHome(getTempDir());%0A%0A%0A        File dst = new File(JMeterUtils.getJMeterHome() + %22/ss.props%22);%0A        InputStream src = DirectoryAnchor.class.getResourceAsStream(%22/kg/apc/jmeter/bin/saveservice.properties%22);%0A        try %7B%0A            Files.copy(src, dst.toPath(), StandardCopyOption.REPLACE_EXISTING
 );%0A 
@@ -1076,17 +1076,16 @@
 eption e
-x
 ) %7B%0A    
@@ -1096,84 +1096,94 @@
     
-ex.printStackTrace(System.err);%0A        %7D%0A%0A        assert propsFile != null;
+throw new RuntimeException(%22Failed to copy file %22 + src + %22 to %22 + dst, e);%0A        %7D%0A
 %0A   
@@ -1224,17 +1224,11 @@
 ies(
-propsFile
+dst
 .get
@@ -1248,57 +1248,8 @@
 ));%0A
-        JMeterUtils.setJMeterHome(getTempDir());%0A
     
@@ -2496,499 +2496,196 @@
     
+%7D%0A%0A
     
-File dst = new File(JMeterUtils.getJMeterHome() + %22/ss.props%22);%0A        InputStream src = DirectoryAnchor.class.getResourceAsStream(%22/kg/apc/jmeter/bin/saveservice.properties%22);%0A        try %7B%0A            Files.copy(src, dst.toPath(), StandardCopyOption.REPLACE_EXISTING);%0A        %7D catch (IOException e) %7B%0A            throw new RuntimeException(%22Failed to copy file %22 + src + %22 to %22 + dst, e);%0A        %7D%0A    %7D%0A%0A    public static String getTempD
+public static String getTempDir() %7B%0A        Path f = null;%0A        try %7B%0A            File path = new File(System.getProperty(%22java.io.tmpdir%22) + %22/jpgc%22);%0A            path.mkd
 ir
+s
 ()
- %7B%0A        Path f = null;%0A        try %7B
+;
 %0A   
@@ -2727,14 +2727,26 @@
 ory(
-%22jpgc/
+path.toPath(), %22ut
 %22);%0A
@@ -2795,26 +2795,66 @@
     
-e.printStackTrace(
+throw new RuntimeException(%22Failed to get new temp dir%22, e
 );%0A 

Fix paths