package com.priusis.util;

import java.io.*;
import java.util.Properties;

/**
 * @author yangli
 * @since 2021/09/11
 */
public final class SysConfigUtil {
    private SysConfigUtil() {

    }

    public static String getProperty(String key) throws IOException {
        return getProperty(key, null);
    }

    public static String getProperty(String key, String defaultVal) throws IOException {
        return loadProperties(configFile()).getProperty(key, defaultVal);
    }

    public static String saveProperty(String key, String val) throws IOException {
        File file = configFile();
        Properties properties = loadProperties(file);
        String oldVal = properties.getProperty(key);
        properties.setProperty(key, val);
        try (OutputStream out = new FileOutputStream(file)) {
            properties.store(out, null);
        }
        return oldVal;
    }

    private static Properties loadProperties(File file) throws IOException {
        try (InputStream in = new FileInputStream(file)) {
            Properties properties = new Properties();
            properties.load(in);
            return properties;
        }
    }

    private static File configFile() throws IOException {
        File dir = new File(System.getProperty("user.home") + File.separator + ".haikang");
        if (!dir.exists()) dir.mkdirs();
        File file = new File(dir, File.separator + "config.properties");
        if (!file.exists()) file.createNewFile();
        return file;
    }
}
