package com.btk5h.skriptmirror;

import ch.njol.skript.Skript;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class LibraryLoader {
  private static ClassLoader classLoader = LibraryLoader.class.getClassLoader();

  private static final PathMatcher MATCHER =
      FileSystems.getDefault().getPathMatcher("glob:**/*.jar");

  private static class LibraryVisitor extends SimpleFileVisitor<Path> {
    private List<URL> urls = new ArrayList<>();

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      if (MATCHER.matches(file)) {
        Skript.info("Loaded external library " + file.getFileName());
        urls.add(file.toUri().toURL());
      }
      return super.visitFile(file, attrs);
    }

    public URL[] getUrls() {
      return urls.toArray(new URL[urls.size()]);
    }
  }

  public static void loadLibraries() throws IOException {
    Path dataFolder = SkriptMirror.getInstance().getDataFolder().toPath();
    if (Files.isDirectory(dataFolder)) {
      LibraryVisitor visitor = new LibraryVisitor();
      Files.walkFileTree(dataFolder, visitor);
      classLoader = new URLClassLoader(visitor.getUrls(), LibraryLoader.class.getClassLoader());
    }
  }

  public static ClassLoader getClassLoader() {
    return classLoader;
  }
}

@@ -1377,24 +1377,78 @@
 sLoader());%0A
+    %7D else %7B%0A      Files.createDirectory(dataFolder);%0A
     %7D%0A  %7D%0A%0A 

Create skript-mirror data folder by default