package com.intellij.perlplugin;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.impl.ProjectRootManagerImpl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by ELI-HOME on 24-May-15.
 * Perl CLI Util - please put all CLI controls here
 */
public class PerlCli {

    public static String runFile(final Project project, String filePath) {
        String result = "";
        try {
            String path = new File(filePath).getPath().replaceFirst("file:\\\\", "");
            if (Utils.debug) {
                Utils.print("running: perl " + "\"" + path + "\"");
            }
            String cmd = getPerlPath(project);
            String[] params = {cmd, "\"" + path + "\""};

            Process p = Runtime.getRuntime().exec(params);
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            result = printStream(result, input);
            result = printStream(result, err);
            int resultCode = p.waitFor();
            if (resultCode != 0) {
                throw new Exception("Failed to run perl - Code (" + resultCode + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String executeCode(Project project, String code) {
        String result = "";
        try {
            String cmd = ((project == null) ? getPerlPath("") : getPerlPath(project));
            String[] params = {cmd, "-e", code};

            Process p = Runtime.getRuntime().exec(params);
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            result = printStream(result, input);
            result = printStream(result, err);
            int resultCode = p.waitFor();
            if (resultCode != 0) {
                throw new Exception("Failed to run perl - Code (" + resultCode + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String printStream(String result, BufferedReader input) throws IOException {
        String line;
        while ((line = input.readLine()) != null) {
            Utils.print(result += line);
        }
        input.close();
        return result;
    }

    public static String getVersionString(Project project) {
        return executeCode(project, "\"use Config;print $Config{version}\"");
    }

    public static void main(String[] args) {
        PerlCli.getVersionString(null);
    }

    private static String getSdkHome(Project project) {
        Sdk sdk = ProjectRootManagerImpl.getInstance(project).getProjectSdk();
        if (sdk == null) {
            return null;
        }
        return sdk.getHomePath();
    }

    /**
     * @param project
     * @return perl's executable file full path
     */
    public static String getPerlPath(Project project) {
        String path = null;
        if (project != null) {
            Sdk sdk = ProjectRootManagerImpl.getInstance(project).getProjectSdk();
            if (sdk != null) {
                return getPerlPath(sdk.getHomePath());
            }else{
                getPerlPath("");
            }
        }
        return path;
    }

    public static String getPerlPath(String sdkHome) {
        String path = null;
        Utils.OSType os = Utils.getOperatingSystemType();
        if (sdkHome == null || sdkHome.isEmpty()) {
            switch (os) {
                case Linux:
                    path = "/usr/";
                case Windows:
                case MacOS:
                case Other:
                    path = System.getenv("PERL_HOME");
            }
        } else {
            path = sdkHome;
        }
        if (!path.endsWith("/") && !path.endsWith("\\")) {
            path += "/";
        }
        return path + "bin/perl";
    }
}

@@ -1719,16 +1719,114 @@
  code%7D;%0A
+            if(cmd == null)%7B%0A                throw new Exception(%22can't find perl%22);%0A            %7D
 %0A       
@@ -2390,35 +2390,43 @@
         
-e.printStackTrac
+Utils.alert(e.getMessag
 e()
+)
 ;%0A      
@@ -3961,24 +3961,51 @@
  = %22/usr/%22;%0A
+                    break;%0A
             
@@ -4194,32 +4194,115 @@
 Home;%0A        %7D%0A
+        if(path == null)%7B%0A            return %22%22;//TODO::Handle Exception%0A        %7D%0A
         if (!pat

handle null pointer