package com.muchinfo.mtp3century.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Component
public class ExternalResourceBundle {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${custom.i18n.baseDir}")
    private String baseDir; // 从 application.yml 读取外部目录

    public ResourceBundle getBundle(String baseName, Locale locale) {
        return ResourceBundle.getBundle(baseName, locale, new ResourceBundle.Control() {
            @Override
            public List<String> getFormats(String baseName) {
                return Collections.singletonList("properties");
            }

            @Override
            public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
                    throws IOException {
                String bundleName = toBundleName(baseName, locale);
                File file = new File(baseDir, bundleName + ".properties");
                log.debug("message file:" + file.getPath());
                if (file.exists()) {
                    log.debug("external message files exists");
                    try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "ISO-8859-1")) {
                        return new PropertyResourceBundle(reader);
                    }
                } else {
                    // 如果外部文件不存在，则尝试从 classpath 加载
                    log.debug("external message files not exists, load from classpath");
                    InputStream inputStream = loader.getResourceAsStream(bundleName + ".properties");
                    if (inputStream != null) {
                        try (InputStreamReader reader = new InputStreamReader(inputStream, "ISO-8859-1")) {
                            return new PropertyResourceBundle(reader);
                        }
                    }
                }
                return null;
            }
        });
    }
}
