package cn.iocoder.yudao.framework.security.utils;

import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.Map;

public class MyReadApplicationUtils {

    private static MyReadApplicationUtils myReadApplicationUtils;
    private static String userByToken;
    private static String appkey;
    private static String userByrefresh;

    private MyReadApplicationUtils() {

    }

    public static MyReadApplicationUtils getInstance() {
        if (myReadApplicationUtils == null) {
            myReadApplicationUtils = new MyReadApplicationUtils();
        }
        return myReadApplicationUtils;
    }

    public static String getUserByToken() {
        if (null == userByToken || "".equals(userByToken)) {
            readApplication();
        }
        return userByToken;
    }

    public static String getRefreByToken() {
        if (null == userByrefresh || "".equals(userByrefresh)) {
            readApplication();
        }
        return userByrefresh;
    }

    public static String getAppkey() {
        if (null == appkey || "".equals(appkey)) {
            readApplication();
        }
        return appkey;
    }

    public static void readApplication() {
        // 1. 加载 application.yml 文件
        Yaml yaml = new Yaml();
        InputStream inputStream = MyReadApplicationUtils.class
                .getClassLoader()
                .getResourceAsStream("pttokeninfo.yml");

        if (inputStream == null) {
            throw new RuntimeException("pttokeninfo.yml 文件未找到！");
        }

        // 2. 解析 YAML 为 Map
        Map<String, Object> yamlMap = yaml.load(inputStream);

        // 3. 提取 pttoken 配置
        Map<String, Object> pttokenConfig = (Map<String, Object>) yamlMap.get("pttoken");
        if (pttokenConfig == null) {
            throw new RuntimeException("pttoken 配置未找到！");
        }

        // 4. 获取具体配置项
        userByToken = (String) pttokenConfig.get("user-by-token");
        appkey = (String) pttokenConfig.get("appkey");

    }
}
