package com.zombie.game.server;

import com.google.gson.JsonObject;

/**
 * Utility class for extracting values from JSON messages / 工具类，用于从JSON消息中提取值
 */
public class MessageUtils {

    // Get string value from JSON with default / 从JSON获取字符串值，带默认值
    public static String getString(JsonObject data, String key, String defaultValue) {
        if (data == null || !data.has(key) || data.get(key).isJsonNull()) {
            return defaultValue;
        }
        try {
            return data.get(key).getAsString();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    // Get string value from JSON (null default) / 从JSON获取字符串值（默认null）
    public static String getString(JsonObject data, String key) {
        return getString(data, key, null);
    }

    // Get float value from JSON with default / 从JSON获取浮点数值，带默认值
    public static float getFloat(JsonObject data, String key, float defaultValue) {
        if (data == null || !data.has(key) || data.get(key).isJsonNull()) {
            return defaultValue;
        }
        try {
            return data.get(key).getAsFloat();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    // Get int value from JSON with default / 从JSON获取整数值，带默认值
    public static int getInt(JsonObject data, String key, int defaultValue) {
        if (data == null || !data.has(key) || data.get(key).isJsonNull()) {
            return defaultValue;
        }
        try {
            return data.get(key).getAsInt();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    // Get boolean value from JSON with default / 从JSON获取布尔值，带默认值
    public static boolean getBoolean(JsonObject data, String key, boolean defaultValue) {
        if (data == null || !data.has(key) || data.get(key).isJsonNull()) {
            return defaultValue;
        }
        try {
            return data.get(key).getAsBoolean();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    // Check if all required keys are present and non-null / 检查所有必需键是否存在且非空
    public static boolean hasRequired(JsonObject data, String... keys) {
        if (data == null) return false;
        for (String key : keys) {
            if (!data.has(key) || data.get(key).isJsonNull()) {
                return false;
            }
        }
        return true;
    }
}
