package com.fujica.abk.api;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

/**
 * 缓存工具类
 */
public class cache {
    private static final String PREF_NAME = "app_cache";
    private static final String KEY_TOKEN = "token";

    /**
     * 获取Preferences实例
     */
    private static Preferences getPreferences(Context context) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context.getApplicationContext());
        return databaseHelper.getPreferences(PREF_NAME);
    }

    /**
     * 获取Token
     */
    public static String getToken(Context context) {
        try {
            Preferences preferences = getPreferences(context);
            if (preferences != null) {
                return preferences.getString(KEY_TOKEN, "");
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 保存Token
     */
    public static void setToken(Context context, String token) {
        try {
            Preferences preferences = getPreferences(context);
            if (preferences != null) {
                preferences.putString(KEY_TOKEN, token);
                preferences.flushSync();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 登出，清除Token
     */
    public static void logout(Context context) {
        try {
            Preferences preferences = getPreferences(context);
            if (preferences != null) {
                preferences.delete(KEY_TOKEN);
                preferences.flushSync();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

