package xdean.tool.api;

import static xdean.jex.util.log.LogUtil.log;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.Properties;

public class Config {
  private static final Properties CONFIG = new Properties();
  private static Path configFile;

  public static void locate(Path configPath, Path defaultConfig) {
    try {
      if (Files.notExists(configPath)) {
        if (Files.exists(defaultConfig)) {
          Files.copy(defaultConfig, configPath);
        } else {
          Files.createFile(configPath);
        }
      }
      CONFIG.load(Files.newBufferedReader(configPath));
    } catch (IOException e) {
      log().error("IOException", e);
    }
    log().debug("Load last config: " + CONFIG.toString());
    configFile = configPath;
  }

  public static Optional<String> getProperty(String key) {
    return Optional.ofNullable(CONFIG.getProperty(key));
  }

  public static Optional<String> getProperty(Object key) {
    return getProperty(key.toString());
  }

  public static String getProperty(Object key, String defaultValue) {
    return getProperty(key.toString(), defaultValue);
  }

  public static String getProperty(String key, String defaultValue) {
    return getProperty(key).orElse(defaultValue);
  }

  public static void setProperty(Object key, String value) {
    setProperty(key.toString(), value);
  }

  public static void setProperty(String key, String value) {
    CONFIG.setProperty(key, value);
    save();
  }

  public static void setIfAbsent(Object key, String value) {
    setIfAbsent(key.toString(), value);
  }

  public static void setIfAbsent(String key, String value) {
    if (getProperty(key).isPresent() == false) {
      setProperty(key, value);
    }
  }

  private static synchronized void save() {
    if (configFile == null) {
      return;
    }
    try {
      CONFIG.store(Files.newOutputStream(configFile), "");
    } catch (IOException e) {
      log().error("", e);
    }
  }
}
@@ -98,16 +98,124 @@
 ption;%0D%0A
+import java.net.URI;%0D%0Aimport java.nio.file.FileSystemNotFoundException;%0D%0Aimport java.nio.file.FileSystems;%0D%0A
 import j
@@ -263,16 +263,66 @@
 .Path;%0D%0A
+import java.util.HashMap;%0D%0Aimport java.util.Map;%0D%0A
 import j
@@ -559,24 +559,378 @@
 tConfig) %7B%0D%0A
+    URI uri = configPath.toUri();%0D%0A    try %7B%0D%0A      FileSystems.getFileSystem(uri);%0D%0A    %7D catch (FileSystemNotFoundException e1) %7B%0D%0A      Map%3CString, String%3E env = new HashMap%3C%3E();%0D%0A      env.put(%22create%22, %22true%22);%0D%0A      try %7B%0D%0A        FileSystems.newFileSystem(uri, env);%0D%0A      %7D catch (IOException e) %7B%0D%0A        throw new Error(e);%0D%0A      %7D%0D%0A    %7D%0D%0A
     try %7B%0D%0A 

create FileSystem