package com.wakatime.intellij.plugin;

import com.sun.deploy.net.HttpResponse;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by alanhamlett on 3/21/14.
 */
public class Dependencies {

    private static String pythonLocation = null;
    private static String resourcesLocation = null;
    private static String cliLocation = null;

    public static boolean isPythonInstalled() {
        return Dependencies.getPythonLocation() != null;
    }

    public static String getResourcesLocation() {
        if (Dependencies.resourcesLocation == null)
            resourcesLocation = WakaTime.class.getResource("WakaTime.class").getPath()
                    .replaceFirst("file:", "")
                    .replaceAll("%20", " ")
                    .replaceFirst("com"+File.separator+"wakatime"+File.separator+"intellij"+File.separator+"plugin"+File.separator+"WakaTime.class", "")
                    .replaceFirst("WakaTime.jar!"+File.separator, "")+"WakaTime-resources";
        return Dependencies.resourcesLocation;
    }

    public static String getPythonLocation() {
        if (Dependencies.pythonLocation != null)
            return Dependencies.pythonLocation;
        String []paths = new String[] {
                "pythonw",
                "python",
                "usr/bin/python",
                "\\python37\\pythonw",
                "\\python36\\pythonw",
                "\\python35\\pythonw",
                "\\python34\\pythonw",
                "\\python33\\pythonw",
                "\\python32\\pythonw",
                "\\python31\\pythonw",
                "\\python30\\pythonw",
                "\\python27\\pythonw",
                "\\python26\\pythonw",
                "\\python37\\python",
                "\\python36\\python",
                "\\python35\\python",
                "\\python34\\python",
                "\\python33\\python",
                "\\python32\\python",
                "\\python31\\python",
                "\\python30\\python",
                "\\python27\\python",
                "\\python26\\python",
        };
        for (int i=0; i<paths.length; i++) {
            try {
                Runtime.getRuntime().exec(paths[i]);
                Dependencies.pythonLocation = paths[i];
                break;
            } catch (Exception e) { }
        }
        return Dependencies.pythonLocation;
    }

    public static boolean isCLIInstalled() {
        File cli = new File(Dependencies.getCLILocation());
        return (cli.exists() && !cli.isDirectory());
    }

    public static String getCLILocation() {
        return Dependencies.getResourcesLocation()+File.separator+"wakatime-master"+File.separator+"wakatime-cli.py";
    }

    public static void installCLI() {
        File cli = new File(Dependencies.getCLILocation());
        if (!cli.getParentFile().getParentFile().exists())
            cli.getParentFile().getParentFile().mkdirs();

        URL url = null;
        try {
            url = new URL("https://codeload.github.com/wakatime/wakatime/zip/master");
        } catch (MalformedURLException e) { }
        String zipFile = cli.getParentFile().getParentFile().getAbsolutePath()+File.separator+"wakatime-cli.zip";
        File outputDir = cli.getParentFile().getParentFile();

        // download wakatime-master.zip file
        ReadableByteChannel rbc = null;
        FileOutputStream fos = null;
        try {
            rbc = Channels.newChannel(url.openStream());
            fos = new FileOutputStream(zipFile);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            Dependencies.unzip(zipFile, outputDir);
            File oldZipFile = new File(zipFile);
            oldZipFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void unzip(String zipFile, File outputDir) throws IOException {
        if(!outputDir.exists())
            outputDir.mkdirs();

        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(outputDir, fileName);

            if (ze.isDirectory()) {
                // System.out.println("Creating directory: "+newFile.getParentFile().getAbsolutePath());
                newFile.mkdirs();
            } else {
                // System.out.println("Extracting File: "+newFile.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }

            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
    }
}

@@ -733,25 +733,69 @@
 ion == null)
+ %7B%0A            String separator = %22%5B%5C%5C%5C%5C/%5D%22;
 %0A
-
             
@@ -999,22 +999,19 @@
 st(%22com%22
-+File.
+ + 
 separato
@@ -1003,33 +1003,35 @@
 com%22 + separator
-+
+ + 
 %22wakatime%22+File.
@@ -1024,22 +1024,19 @@
 akatime%22
-+File.
+ + 
 separato
@@ -1036,17 +1036,19 @@
 eparator
-+
+ + 
 %22intelli
@@ -1049,22 +1049,19 @@
 ntellij%22
-+File.
+ + 
 separato
@@ -1065,17 +1065,19 @@
 ator
-+
+ + 
 %22plugin%22
 +Fil
@@ -1072,22 +1072,19 @@
 %22plugin%22
-+File.
+ + 
 separato
@@ -1084,17 +1084,19 @@
 eparator
-+
+ + 
 %22WakaTim
@@ -1158,22 +1158,19 @@
 me.jar!%22
-+File.
+ + 
 separato
@@ -1175,17 +1175,19 @@
 tor, %22%22)
-+
+ + 
 %22WakaTim
@@ -1200,16 +1200,26 @@
 urces%22;%0A
+        %7D%0A
         

fix #1 Illegal/unsupported escape sequence with Windows path separator in regex