package com.tofly.feesapi.common.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * Author  Administrator
 *
 * @Date 2026-03-20 13:44 （创建时间）
 * @Version 1.0 （版本号）
 */
public class ConfigManager {
    private Properties properties = new Properties();
    private static ConfigManager instance;

    // Singleton pattern
    private ConfigManager() {
        loadProperties();
    }

    public static ConfigManager getInstance() {
        if (instance == null) {
            instance = new ConfigManager();
        }
        return instance;
    }

    // Method 1: Load from classpath (src/main/resources)
    private void loadProperties() {
        try (InputStream input = getClass().getClassLoader()
                .getResourceAsStream("config.properties")
        ) {

            if (input == null) {
                System.out.println("Sorry, unable to find config.properties");
                return;
            }
            try (java.io.Reader reader = new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8)) {
                properties.load(reader);
            }
           // properties.load(bufferedReader);

            String chinese = properties.getProperty("config1");
            System.out.println(  new String(chinese.getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("Configuration loaded successfully!");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // Method 2: Load from external file system
    public void loadFromFile(String filePath) {
        try (FileInputStream input = new FileInputStream(filePath)) {
            properties.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // Get property with default value
    public String getProperty(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }

    // Get property (throws exception if not found)
    public String getProperty(String key) {
        String value = properties.getProperty(key);
        if (value == null) {
            throw new RuntimeException("Property '" + key + "' not found in config file");
        }
        return value;
    }

    // Convenience methods for common types
    public int getIntProperty(String key) {
        return Integer.parseInt(getProperty(key));
    }

    public boolean getBooleanProperty(String key) {
        return Boolean.parseBoolean(getProperty(key));
    }

    // Display all properties
    public void printAllProperties() {
        properties.forEach((key, value) ->
                System.out.println(key + " = " + value));
    }
        /*获取所有属性*/
    public List<Map<String,String>> GetAllProperties() {
        List<Map<String,String>> propertiesList = new ArrayList<>();

        properties.forEach((key, value) ->{
            Map<String, String> map = new HashMap<>();
                map.put("key", convertToUtf8(key.toString()));
                map.put("value", convertToUtf8(value.toString()));
                propertiesList.add(map);
             }
             /**/
        );
        return  propertiesList;
    }

    /**
     * 根据 key 修改配置属性（仅内存中修改，不保存到文件）
     */
    public void setProperty(String key, String value) {
        properties.setProperty(key, value);
    }

    /**
     * 根据 key 修改配置并保存到文件
     * @param key 配置键
     * @param value 配置值
     * @param filePath 配置文件路径（绝对路径或相对路径）
     */
    public void setPropertyAndSave(String key, String value, String filePath) {
        // 先修改内存中的属性
        properties.setProperty(key, value);

        // 保存到文件
        try (FileOutputStream output = new FileOutputStream(filePath)) {
            properties.store(output, "Updated property: " + key);
            System.out.println("Configuration saved successfully!");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 字符串转码（ISO-8859-1 -> UTF-8）
     */
    public String convertToUtf8(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        try {
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
            return str;
        }
    }

}
