package com.reason.bs;

import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class BsConfig {
    private static Pattern DEPS_REGEXP = Pattern.compile(".*\"bs-dependencies\":\\s*\\[(.*?)].*");

    private final String[] m_deps;

    private BsConfig(String[] deps) {
        m_deps = new String[deps.length + 1];
        System.arraycopy(deps, 0, m_deps, 0, deps.length);
        m_deps[deps.length] = "bs-platform/lib/ocaml/js.ml"; // all files but the ones with _ ?
    }

    @NotNull
    static BsConfig read(@NotNull VirtualFile bsconfig) {
        try {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(bsconfig.getInputStream()))) {
                // Quick and dirty code to read json values from bsconfig
                StringBuilder content = new StringBuilder();
                reader.lines().forEach(line -> content.append(line.trim()));
                // extract bs dependencies
                Matcher matcher = DEPS_REGEXP.matcher(content.toString());

                String[] deps = null;
                if (matcher.matches()) {
                    String[] tokens = matcher.group(1).split(",");
                    deps = new String[tokens.length];
                    for (int i = 0; i < tokens.length; i++) {
                        String token = tokens[i].trim();
                        deps[i] = token.substring(1, token.length() - 1) + "/lib";
                    }
                }

                return new BsConfig(deps);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    boolean accept(String canonicalPath) {
        if (canonicalPath.contains("node_modules") && m_deps != null) {
            for (String dep : m_deps) {
                if (canonicalPath.contains(dep)) {
                    return true;
                }
            }
            return false;
        }

        return true;
    }
}

@@ -103,16 +103,59 @@
 NotNull;
+%0Aimport org.jetbrains.annotations.Nullable;
 %0A%0Aimport
@@ -480,16 +480,26 @@
 sConfig(
+@Nullable 
 String%5B%5D
@@ -499,32 +499,117 @@
 tring%5B%5D deps) %7B%0A
+        if (deps == null) %7B%0A            m_deps = new String%5B0%5D;%0A        %7D else %7B%0A    
         m_deps =
@@ -638,16 +638,20 @@
 h + 1%5D;%0A
+    
         
@@ -705,24 +705,28 @@
 h);%0A        
+    
 m_deps%5Bdeps.
@@ -801,16 +801,26 @@
 ith _ ?%0A
+        %7D%0A
     %7D%0A%0A 

Fix a NPE in BsConfig