package com.gh.gamecenter.login.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import com.sina.weibo.sdk.auth.Oauth2AccessToken;

/**
 * Created by khy on 2016/11/24.
 * 该类定义了微博授权时所需要的参数。
 */
public class AccessTokenKeeper {
    private static final String PREFERENCES_NAME = "com_weibo_sdk_android";

    private static final String KEY_UID = "uid";
    private static final String KEY_USERNAME = "userName";
    private static final String KEY_ACCESS_TOKEN = "access_token";
    private static final String KEY_EXPIRES_IN = "expires_in";
    private static final String KEY_REFRESH_TOKEN = "refresh_token";

    /**
     * 保存 Token 对象到 SharedPreferences。
     *
     * @param context 应用程序上下文环境
     * @param token   Token 对象
     */
    public static void writeAccessToken(Context context, Oauth2AccessToken token) {
        if (null == context || null == token) {
            return;
        }

        SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(KEY_UID, token.getUid());
        editor.putString(KEY_USERNAME, token.getScreenName());
        editor.putString(KEY_ACCESS_TOKEN, token.getAccessToken());
        editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
        editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
        editor.apply();
    }

    /**
     * 从 SharedPreferences 读取 Token 信息。
     *
     * @param context 应用程序上下文环境
     * @return 返回 Token 对象
     */
    public static Oauth2AccessToken readAccessToken(Context context) {
        if (null == context) {
            return null;
        }

        SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
        Bundle args = new Bundle();
        args.putString(KEY_UID, pref.getString(KEY_UID, ""));
        args.putString(KEY_USERNAME, pref.getString(KEY_USERNAME, ""));
        args.putString(KEY_ACCESS_TOKEN, pref.getString(KEY_ACCESS_TOKEN, ""));
        args.putString(KEY_REFRESH_TOKEN, pref.getString(KEY_REFRESH_TOKEN, ""));
        args.putLong(KEY_EXPIRES_IN, pref.getLong(KEY_EXPIRES_IN, 0));
        return Oauth2AccessToken.parseAccessToken(args);
    }

    /**
     * 清空 SharedPreferences 中 Token信息。
     *
     * @param context 应用程序上下文环境
     */
    public static void clear(Context context) {
        if (null == context) {
            return;
        }

        SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.clear();
        editor.apply();
    }
}
