package com.jetbrains.python.sdk;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import org.jetbrains.annotations.NonNls;

import java.io.File;
import java.util.*;

/**
 * @author yole
 */
public class WinPythonSdkFlavor extends PythonSdkFlavor {
  @NonNls static final private String PYTHON_STR = "python";

  public static WinPythonSdkFlavor INSTANCE = new WinPythonSdkFlavor();

  private WinPythonSdkFlavor() {
  }

  @Override
  public Collection<String> suggestHomePaths() {
    Set<String> candidates = new TreeSet<String>();
    findSubdirInstallations(candidates, "C:\\", PYTHON_STR, "python.exe");
    findSubdirInstallations(candidates, "C:\\Program Files\\", PYTHON_STR, "python.exe");
    findSubdirInstallations(candidates, "C:\\", "jython", "jython.bat");
    findInPath(candidates, "python.exe");
    findInPath(candidates, "jython.bat");
    return candidates;
  }

  public static void findInPath(Collection<String> candidates, String exeName) {
    final String path = System.getenv("PATH");
    for (String pathEntry : StringUtil.split(path, ";")) {
      if (pathEntry.startsWith("\"") && pathEntry.endsWith("\"")) {
        pathEntry = pathEntry.substring(1, pathEntry.length()-2);
      }
      File f = new File(pathEntry, exeName);
      if (f.exists()) {
        candidates.add(f.getPath());
      }
    }
  }

  private static void findSubdirInstallations(Collection<String> candidates, String rootDir, String dir_prefix, String exe_name) {
    VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(rootDir);
    if (rootVDir != null) {
      rootVDir.refresh(false, false);
      for (VirtualFile dir : rootVDir.getChildren()) {
        if (dir.isDirectory() && dir.getName().toLowerCase().startsWith(dir_prefix)) {
          VirtualFile python_exe = dir.findChild(exe_name);
          if (python_exe != null) candidates.add(python_exe.getPath());
        }
      }
    }
  }

  @Override
  public void addPredefinedEnvironmentVariables(Map<String, String> envs) {
    final String encoding = EncodingManager.getInstance().getDefaultCharset().name();
    envs.put("PYTHONIOENCODING", encoding);
  }
}

@@ -28,16 +28,62 @@
 n.sdk;%0A%0A
+import com.intellij.openapi.util.io.FileUtil;%0A
 import c
@@ -356,17 +356,96 @@
 va.util.
-*
+Collection;%0Aimport java.util.Map;%0Aimport java.util.Set;%0Aimport java.util.TreeSet
 ;%0A%0A/**%0A 
@@ -1578,16 +1578,49 @@
 tes.add(
+FileUtil.toSystemIndependentName(
 f.getPat
@@ -1615,32 +1615,33 @@
 ame(f.getPath())
+)
 ;%0A      %7D%0A    %7D%0A
@@ -2175,16 +2175,49 @@
 tes.add(
+FileUtil.toSystemIndependentName(
 python_e
@@ -2229,16 +2229,17 @@
 tPath())
+)
 ;%0A      

normalize file names when collecting suggested interpreters (PY-1931)