package com.sf.sdk.demo;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.sf.sdk.SFAppUpdateListener;
import com.sf.sdk.SFConsumer;
import com.sf.sdk.SFFirebaseMessagingListener;
import com.sf.sdk.SFFirebaseRemoteConfigListener;
import com.sf.sdk.SFLocaleCurrencyListener;
import com.sf.sdk.SFNetworkStateListener;
import com.sf.sdk.SFPlatform;
import com.sf.sdk.SFRequestListener;
import com.sf.sdk.SFRequestResultListener;
import com.sf.sdk.SFResultListener;
import com.sf.sdk.SFSDKListener;
import com.sf.sdk.config.AnalyticsType;
import com.sf.sdk.config.CommunityType;
import com.sf.sdk.config.RoleDataType;
import com.sf.sdk.data.SFAppUpdateInfo;
import com.sf.sdk.data.SFDeepLink;
import com.sf.sdk.data.SFFirebaseMessage;
import com.sf.sdk.data.SFGameSnapshot;
import com.sf.sdk.data.SFLeaderboard;
import com.sf.sdk.data.SFOrder;
import com.sf.sdk.data.SFOrderRecord;
import com.sf.sdk.data.SFProductDetails;
import com.sf.sdk.data.SFProfile;
import com.sf.sdk.data.SFRoleData;
import com.sf.sdk.data.SFShareContent;
import com.sf.sdk.data.SFSnapshotMetadata;
import com.sf.sdk.data.SFUser;
import com.sf.sdk.demo.ads.MixedAdsActivity;
import com.sf.sdk.demo.safety.SafetyActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class MainActivity extends BaseActivity implements View.OnClickListener, SFNetworkStateListener {

    private static final String TEST_EVENT = "event_test";
    private static final String GOOGLE_PLAY_URL = "https://play.google.com/store/apps/details?id=";
    private static final String PICTURE_URL = "https://pic.rmb.bdstatic.com/bjh/3ea18f1b6d66/250218/5568dc783dbdfd6546f319fa13a505aa.jpeg";

    private static final String SHARE_URL = GOOGLE_PLAY_URL + BuildConfig.APPLICATION_ID;
    private static final String SHARE_TEXT = "Come play this level with me!";

    private static final String ROLE_ID = "role_1";
    private static final String ROLE_NAME = "test_role";
    private static final String ROLE_LEVEL = "1";
    private static final String SERVER_ID = "server_1";
    private static final String SERVER_NAME = "test_server";
    private static final String VIP_LEVEL = "1";

    private static final String WEEKLY_RANKING = "weekly_ranking";

    private SFUser user;
    private String productId;
    private TextView tvUserId;
    private ComponentName componentName;
    private List<ComponentName> componentNames;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

    @Override
    protected boolean showHomeUp() {
        return false;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.content_main;
    }

    @Override
    protected void initViews() {
        findViewById(R.id.button_init).setOnClickListener(this);
        findViewById(R.id.button_login).setOnClickListener(this);
        findViewById(R.id.button_pay).setOnClickListener(this);
        findViewById(R.id.button_restore).setOnClickListener(this);
        findViewById(R.id.button_pre_registration).setOnClickListener(this);
        findViewById(R.id.button_refund_warning).setOnClickListener(this);
        findViewById(R.id.button_refund_orders).setOnClickListener(this);
        findViewById(R.id.button_role_upload).setOnClickListener(this);
        findViewById(R.id.button_track_event).setOnClickListener(this);
        findViewById(R.id.button_logout).setOnClickListener(this);
        findViewById(R.id.button_open_community).setOnClickListener(this);
        findViewById(R.id.button_service_center).setOnClickListener(this);
        findViewById(R.id.button_user_profile).setOnClickListener(this);
        findViewById(R.id.button_write_snapshot).setOnClickListener(this);
        findViewById(R.id.button_read_snapshot).setOnClickListener(this);
        findViewById(R.id.button_query_leaderboard).setOnClickListener(this);
        findViewById(R.id.button_update_score).setOnClickListener(this);
        findViewById(R.id.button_deep_link).setOnClickListener(this);
        findViewById(R.id.button_web_url).setOnClickListener(this);
        findViewById(R.id.button_native_share).setOnClickListener(this);
        findViewById(R.id.button_game_review).setOnClickListener(this);
        findViewById(R.id.button_locale_currency).setOnClickListener(this);
        findViewById(R.id.button_firebase_token).setOnClickListener(this);
        findViewById(R.id.button_delete_account).setOnClickListener(this);
        findViewById(R.id.button_test_crash).setOnClickListener(this);
        findViewById(R.id.button_ads).setOnClickListener(this);
        findViewById(R.id.button_safety).setOnClickListener(this);
        findViewById(R.id.button_switch_icon).setOnClickListener(this);

        tvUserId = findViewById(R.id.sdk_user_id);
        tvUserId.setOnClickListener(this);
        TextView tvSdkVersion = findViewById(R.id.sdk_version);
        tvSdkVersion.setText(String.format("%s(v%s)", SFPlatform.getInstance().getPlatformName(), SFPlatform.getInstance().getSdkVersion()));

        productId = Config.PRODUCT_ID_2;
        initSDK();

        // 如果app未启动，deeplink唤起app时触发
        handleIntent(getIntent());

        generateKeyHash(getApplicationContext());

        JSONObject superProperties = new JSONObject();
        try {
            superProperties.putOpt("user_name", "Test_001");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        SFPlatform.getInstance().getSofishService().setSuperProperties(superProperties);
        SFPlatform.getInstance().getFirebaseService().addRemoteConfigListener(new SFFirebaseRemoteConfigListener() {
            @Override
            public void onRemoteConfigLoaded(boolean successful) {
                requestAppUpdate();
            }

            @Override
            public void onRemoteConfigUpdate(Set<String> updatedKeys) {

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 如果app已经启动，deeplink唤起app时触发
        handleIntent(intent);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.button_init) {
            initSDK();
        } else if (id == R.id.button_login) {
            login();
        } else if (id == R.id.button_pay) {
            payment();
        } else if (id == R.id.button_restore) {
            restorePurchases();
        } else if (id == R.id.button_pre_registration) {
            preRegistration();
        } else if (id == R.id.button_refund_warning) {
            refundWarning();
        } else if (id == R.id.button_refund_orders) {
            refundOrders();
        } else if (id == R.id.button_role_upload) {
            uploadRoleData();
        } else if (id == R.id.button_open_community) {
            openCommunity();
        } else if (id == R.id.button_service_center) {
            openServiceCenter();
        } else if (id == R.id.button_user_profile) {
            queryUserProfile();
        } else if (id == R.id.button_write_snapshot) {
            writeSnapshot();
        } else if (id == R.id.button_read_snapshot) {
            readSnapshot();
        } else if (id == R.id.button_query_leaderboard) {
            queryLeaderboards();
        } else if (id == R.id.button_update_score) {
            submitPlayerScore();
        } else if (id == R.id.button_deep_link) {
            handleDeepLink();
        } else if (id == R.id.button_web_url) {
            openBrowser();
        } else if (id == R.id.button_native_share) {
            shareNative();
        } else if (id == R.id.button_game_review) {
            launchGameReview();
        } else if (id == R.id.button_locale_currency) {
            queryLocaleCurrency();
        } else if (id == R.id.button_firebase_token) {
            getFirebaseToken();
        } else if (id == R.id.button_track_event) {
            trackEvent();
        } else if (id == R.id.button_logout) {
            logout();
        } else if (id == R.id.button_delete_account) {
            deleteAccount();
        } else if (id == R.id.button_test_crash) {
            testCrash();
        } else if (id == R.id.button_ads) {
            Intent intent = new Intent(this, MixedAdsActivity.class);
            intent.putExtra(Intent.EXTRA_USER, user == null ? null : user.getUid());
            startActivity(intent);
        } else if (id == R.id.button_safety) {
            Intent intent = new Intent(this, SafetyActivity.class);
            startActivity(intent);
        } else if (id == R.id.button_switch_icon) {
            switchIcon();
        } else if (id == R.id.sdk_user_id) {
            if (user != null && copyText(user.getUid())) {
                showToast(getString(R.string.sf_copy_success));
            }
        }
    }

    private void handleIntent(Intent intent) {
        Uri data = intent == null ? null : intent.getData();
        if (data != null) {
            // deeplink 链接以此为例：sofishsdk://app?key1=value1&key2=value2
            // 完整链接
            String url = data.toString();
            // scheme: sofishsdk
            String scheme = data.getScheme();
            // host: app
            String host = data.getHost();
            // 获取key1参数值: value1
            String value1 = data.getQueryParameter("key1");

            showToast(url);
            // Uri 类的详细介绍请参考官方文档：https://developer.android.com/reference/android/net/Uri
        }
    }

    private void initSDK() {
        SFPlatform.getInstance().setDebugMode(true);                    // 正式发布时设置为false
        SFPlatform.getInstance().enableClientDeliveryNotification();    // 启用客户端发货通知(仅针对不依赖服务端通知发货的游戏)
        SFPlatform.getInstance().addNetworkStateListener(this);         // 添加网络状态改变监听
        SFPlatform.getInstance().init(this, new SFSDKListener() {
            @Override
            public void onInitSuccess() {
                // 初始化成功回调
                showToast("初始化成功");
            }

            @Override
            public void onInitFailed(int code, String message) {
                // 初始化失败回调
                // showToast("初始化失败\n" + code + ":" + message);
            }

            @Override
            public void onLoginSuccess(SFUser user) {
                // 登录成功回调
                showToast("登录成功");
                updateUser(user);
            }

            @Override
            public void onLoginSuccessWaitForNetwork(SFUser user) {
                // 登录成功回调(触发登录操作时网络不可用，网络恢复时自动登录)
                showToast("登录成功");
                updateUser(user);
            }

            @Override
            public void onLoginFailed(int code, String message) {
                // 登录失败回调
                // showToast(getString(R.string.login_failed) + "\n" + code + ":" + message);
            }

            @Override
            public void onLinkSuccess(SFUser user) {
                // 账号绑定成功回调
                showToast("绑定成功");
                updateUser(user);
            }

            @Override
            public void onLinkFailed(int code, String message) {
                // 账号绑定失败回调
                // showToast(getString(R.string.link_failed) + "\n" + code + ":" + message);
            }

            @Override
            public void onPaymentSuccess(SFOrder order) {
                // 支付成功回调
                showToast("支付成功: " + order.getProductID());

                // 对于Google推荐订单，由于不是游戏通过正常支付流程发起的，所以没有游戏订单号，需要游戏创建一个新的订单用于存档
                String cpOrderID = order.getCpOrderID();
                if (cpOrderID == null || cpOrderID.length() == 0) {
                    // 根据商品ID创建游戏订单
                    cpOrderID = "order_" + System.currentTimeMillis();
                    // 创建游戏订单后传入cpOrderID
                    order.setCpOrderID(cpOrderID);
                }

                // 通知服务端发货成功(仅针对不依赖服务端通知发货的游戏)
                SFPlatform.getInstance().notifyServerDeliverySuccess(order);
            }

            @Override
            public void onPaymentFailed(int code, String message) {
                // 支付失败回调
                showToast("支付失败\n" + code + ":" + message);
            }

            @Override
            public void onRestoreSuccess(List<SFOrderRecord> success, List<SFOrderRecord> failure) {
                boolean hasSuccess = success != null && !success.isEmpty();
                if (hasSuccess) {
                    List<String> productIds = new ArrayList<>();
                    for (SFOrderRecord record : success) {
                        productIds.add(record.getProductID());
                    }
                    showToast("恢复成功: " + productIds);
                }
                boolean hasFailure = failure != null && !failure.isEmpty();
                if (hasFailure) {
                    List<String> productIds = new ArrayList<>();
                    for (SFOrderRecord record : failure) {
                        productIds.add(record.getProductID());
                    }
                    showToast("恢复失败: " + productIds);
                }
                if (!hasSuccess && !hasFailure) {
                    showToast("没有需要恢复的购买");
                }
            }

            @Override
            public void onRestoreFailed(int code, String message) {
                showToast("恢复购买失败\n" + code + ":" + message);
            }

            @Override
            public void onExitGame() {
                // 退出游戏回调
            }

            @Override
            public void onLogout() {
                // 调用登出接口之后的回调，或者SDK内部触发登出时的回调
                showToast("登出成功");
                updateUser(null);
            }

            @Override
            public void onDeleted() {
                // 调用接口接口之后的回调
                showToast("帐号注销申请已提交");
                updateUser(null);
            }
        });
    }

    private void requestAppUpdate() {
        SFPlatform.getInstance().requestAppUpdate(BuildConfig.VERSION_NAME, new SFAppUpdateListener() {
            @Override
            public void shouldShowAppUpdatePrompt(SFAppUpdateInfo appUpdateInfo) {
                // 展示版本更新内容提示弹窗(强制更新时不允许关闭/取消弹窗)
                showAppUpdateAlertDialog(appUpdateInfo);
            }

            @Override
            public void shouldShowAppInstallPrompt(SFConsumer<Boolean> consumer) {
                // 展示引导用户安装提示弹窗(应用内更新下载完成时引导用户安装)
                new AlertDialog.Builder(activity)
                        .setTitle("Tips")
                        .setMessage("Download complete, please install now.")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 传入用户是否允许安装
                                consumer.accept(true); // 允许安装
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                consumer.accept(false); // 不允许安装
                            }
                        })
                        .show();
            }

            @Override
            public void noUpdateAvailable() {
                // 没有可用更新
            }
        });
    }

    /**
     * 弹出应用更新弹窗(如果是强制更新，请保持弹窗一直显示，如果弹窗消失请在游戏可见时再次弹窗提醒用户)
     *
     * @param appUpdateInfo
     */
    private void showAppUpdateAlertDialog(SFAppUpdateInfo appUpdateInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                .setTitle(appUpdateInfo.getTitle())
                .setMessage(appUpdateInfo.getMessage())
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 打开应用商店
                        appUpdateInfo.openAppStore(activity);
                    }
                });
        if (!appUpdateInfo.isForceUpdate()) {
            builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 如果是软更，用户选择跳过更新时需要通知SDK
                    appUpdateInfo.skipSoftUpdate();
                }
            });
        }
        builder.show();
    }

    @Override
    public void onNetworkStateChanged(boolean isAvailable, String networkType) {
        Log.i("TAG", "Network state changed:" + networkType);
    }

    private void updateUser(SFUser user) {
        this.user = user;
        this.tvUserId.setText(user == null ? null : String.format("User ID:%s", user.getUid()));
    }

    private void login() {
        SFPlatform.getInstance().login(this, false);
        // SFPlatform.getInstance().login(this, AccountType.Google);
    }

    private void payment() {
        CharSequence title = getString(R.string.button_pay);
        CharSequence[] items = new CharSequence[]{Config.PRODUCT_ID_1, Config.PRODUCT_ID_2};
        showSelectorDialog(title, items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String productId = items[which].toString();
                doPay(productId);
            }
        });
    }

    private void doPay(String productId) {
        SFOrder order = new SFOrder();
        order.setProductID(productId);
        order.setProductName(Config.PRODUCT_NAME);
        order.setProductDesc(Config.PRODUCT_DESC);
        order.setPrice(Config.PRODUCT_PRICE);
        order.setCurrency(Config.CURRENCY);
        order.setServerID(SERVER_ID);
        order.setServerName(SERVER_NAME);
        order.setRoleID(ROLE_ID);
        order.setRoleName(ROLE_NAME);
        order.setRoleLevel(ROLE_LEVEL);
        order.setVipLevel(VIP_LEVEL);
        order.setCpOrderID("order_" + System.currentTimeMillis());
        order.setExtra("extra data");
        order.setPayNotifyUrl("http://pay.gameserver.com/pay/notify");    //游戏服务器的支付通知回调地址
        SFPlatform.getInstance().pay(MainActivity.this, order);
    }

    private void restorePurchases() {
        // 恢复已完成的购买(仅恢复非消耗型商品)
        SFPlatform.getInstance().restoreCompletedPurchases();
        // 恢复已完成的购买(可恢复消耗型商品和非消耗型商品)
        SFPlatform.getInstance().restoreCompletedPurchase(productId, new SFRequestResultListener<SFOrderRecord>() {
            @Override
            public void onSuccess(SFOrderRecord data) {
                String orderID = data.getOrderID();
            }

            @Override
            public void onFailed(int code, String message) {

            }
        });
    }

    private void preRegistration() {
        SFPlatform.getInstance().preRegistration(MainActivity.this, new SFRequestResultListener<String>() {
            @Override
            public void onSuccess(String data) {
                String title = getString(R.string.button_pre_registration);
                String message = getString(R.string.sf_error_2013);
                showMessageDialog(title, TextUtils.isEmpty(data) ? message : data);
            }

            @Override
            public void onFailed(int code, String message) {
                showToast(code + ":" + message);
            }
        });
    }

    private void refundWarning() {
        SFPlatform.getInstance().checkRefund(MainActivity.this);
    }

    private void refundOrders() {
        SFPlatform.getInstance().queryRefundOrders(new SFResultListener<List<SFOrderRecord>>() {
            @Override
            public void onResult(List<SFOrderRecord> result) {
                String title = getString(R.string.button_refund_orders);
                showMessageDialog(title, result == null || result.isEmpty() ? "No refund orders" : "Refund orders:" + result.size());
            }
        });
    }

    private void uploadRoleData() {
        CharSequence title = getString(R.string.button_role_upload);
        CharSequence[] items = new CharSequence[]{getString(R.string.button_create_role), getString(R.string.button_enter_game), getString(R.string.button_level_up), getString(R.string.button_exit_game)};
        showSelectorDialog(title, items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int roleDataType = 0;
                if (which == 0) {
                    roleDataType = RoleDataType.CREATE_ROLE;
                } else if (which == 1) {
                    roleDataType = RoleDataType.ENTER_GAME;
                } else if (which == 2) {
                    roleDataType = RoleDataType.LEVEL_UP;
                } else if (which == 3) {
                    roleDataType = RoleDataType.EXIT_GAME;
                }
                submitRoleData(roleDataType);
            }
        });
    }

    private void submitRoleData(@RoleDataType int type) {
        SFRoleData data = new SFRoleData();
        data.setType(type);
        data.setRoleID(ROLE_ID);
        data.setRoleName(ROLE_NAME);
        data.setRoleLevel(ROLE_LEVEL);
        data.setServerID(SERVER_ID);
        data.setServerName(SERVER_NAME);
        data.setVipLevel(VIP_LEVEL);
        data.setCreateTime(System.currentTimeMillis() / 1000);
        data.setLastLevelUpTime(data.getCreateTime());

        SFPlatform.getInstance().submit(this, data, new SFRequestListener() {
            @Override
            public void onSuccess() {
                showToast(getString(R.string.submit_success));
            }

            @Override
            public void onFailed(int code, String message) {
                showToast(message);
            }
        });
    }

    private void openCommunity() {
        CharSequence title = getString(R.string.button_open_community);
        CharSequence[] items = new CharSequence[]{"Discord", "Facebook", "Instagram", "Twitter", "LINE"};
        showSelectorDialog(title, items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String communityType = "";
                if (which == 0) {
                    communityType = CommunityType.Discord;
                } else if (which == 1) {
                    communityType = CommunityType.Facebook;
                } else if (which == 2) {
                    communityType = CommunityType.Instagram;
                } else if (which == 3) {
                    communityType = CommunityType.Twitter;
                } else if (which == 4) {
                    communityType = CommunityType.Line;
                }
                SFPlatform.getInstance().community(communityType, new SFRequestListener() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFailed(int code, String message) {
                        showToast(message);
                    }
                });
            }
        });
    }

    private void openServiceCenter() {
        SFPlatform.getInstance().service(MainActivity.this);
    }

    private void queryUserProfile() {
        SFPlatform.getInstance().queryProfile(MainActivity.this, new SFRequestResultListener<SFProfile>() {
            @Override
            public void onSuccess(SFProfile data) {
                String message = "AccountId: " + data.getAccountId() + "\n" +
                        "Name: " + data.getName() + "\n" +
                        "Email: " + data.getEmail() + "\n" +
                        "Picture: " + data.getPicture();
                showMessageDialog(getString(R.string.button_user_profile), message);
            }

            @Override
            public void onFailed(int code, String message) {
                showToast(message);
            }
        });
    }

    private void writeSnapshot() {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("userId", user.getUid());
        map.put("userName", user.getName());
        map.put("expiredTime", user.getExpiredTime());
        map.put("registerTime", user.getRegisterTime());
        map.put("countryCode", user.getCountryCode());
        map.put("saveTime", sdf.format(new Date()));
        String json = new JSONObject(map).toString();
        SFSnapshotMetadata metadata = new SFSnapshotMetadata.Builder()
                .setDescription("Test Snapshot")
                .build();
        SFPlatform.getInstance().getGameService(this).writeSnapshot(user.getUid(), json.getBytes(StandardCharsets.UTF_8), metadata, true, new SFRequestResultListener<SFGameSnapshot>() {
            @Override
            public void onSuccess(SFGameSnapshot data) {
                showToast("存档保存成功：" + data.getUniqueName());
            }

            @Override
            public void onFailed(int code, String message) {
                showToast("存档保存失败：" + message);
            }
        });
    }

    private void readSnapshot() {
        SFPlatform.getInstance().getGameService(this).readSnapshots(user.getUid(), true, new SFRequestResultListener<SFGameSnapshot>() {
            @Override
            public void onSuccess(SFGameSnapshot data) {
                showToast("存档读取成功：" + new String(data.getSnapshotData()));
            }

            @Override
            public void onFailed(int code, String message) {
                showToast("存档读取失败：" + message);
            }
        });
    }

    private void queryLeaderboards() {
        // SFPlatform.getInstance().getGameService(this).getLeaderboard(WEEKLY_RANKING, new SFRequestResultListener<SFLeaderboard>() {
        //     @Override
        //     public void onSuccess(SFLeaderboard data) {
        //         String message = String.format("%s    %d    %d", data.getPlayerId(), data.getScore(), data.getRank());
        //         showMessageDialog("当前玩家排名", message);
        //     }
        //
        //     @Override
        //     public void onFailed(int code, String message) {
        //         showToast("查询当前玩家排名失败：" + message);
        //     }
        // });
        long timestamp = System.currentTimeMillis() / 1000 / 180;
        SFPlatform.getInstance().getGameService(this).getLeaderboards(WEEKLY_RANKING, 100, timestamp, new SFRequestResultListener<List<SFLeaderboard>>() {
            @Override
            public void onSuccess(List<SFLeaderboard> leaderboards) {
                StringBuilder builder = new StringBuilder();
                if (leaderboards != null && !leaderboards.isEmpty()) {
                    int size = Math.min(10, leaderboards.size());
                    for (int i = 0; i < size; i++) {
                        SFLeaderboard leaderboard = leaderboards.get(i);
                        builder.append("\n");
                        builder.append(String.format("%d    %s    %d", leaderboard.getRank(), leaderboard.getPlayerId(), leaderboard.getScore()));
                    }
                }
                showMessageDialog("玩家排行榜", builder.toString());
            }

            @Override
            public void onFailed(int code, String message) {
                showToast("查询玩家排行榜失败：" + message);
            }
        });
    }

    private void submitPlayerScore() {
        if (user == null) {
            return;
        }
        SFLeaderboard leaderboard = new SFLeaderboard.Builder()
                .setPlayerId(user.getUid())
                .setPlayerName(user.getName())
                .setPictureUrl(PICTURE_URL)
                .setLeaderboardId(WEEKLY_RANKING)
                .setExtra("{\"country\":\"CN\"}")
                .setScore(100)
                .build();
        SFPlatform.getInstance().getGameService(this).submitPlayerScore(leaderboard, new SFRequestResultListener<SFLeaderboard>() {
            @Override
            public void onSuccess(SFLeaderboard data) {
                String message = String.format("%s    %d    %d", data.getPlayerId(), data.getScore(), data.getRank());
                showMessageDialog("当前玩家排名", message);
            }

            @Override
            public void onFailed(int code, String message) {
                showToast("更新当前玩家成绩失败：" + message);
            }
        });
    }

    private void handleDeepLink() {
        SFPlatform.getInstance().setDeepLinkListener(new SFResultListener<SFDeepLink>() {
            @Override
            public void onResult(SFDeepLink deepLink) {
                showMessageDialog(getString(R.string.button_deep_link), deepLink.getUri().toString());
            }
        });
    }

    private void openBrowser() {
        SFPlatform.getInstance().openBrowser("https://www.google.com/");
    }

    private void shareNative() {
        SFShareContent shareContent = new SFShareContent.Builder()
                .setShareContent(SHARE_TEXT)
                .setShareUrl(SHARE_URL)
                .setShareType(SFShareContent.ShareType.TEXT)
                .build();
        SFPlatform.getInstance().shareNative(this, shareContent, new SFRequestListener() {
            @Override
            public void onSuccess() {
                showToast(getString(R.string.share_success));
            }

            @Override
            public void onFailed(int code, String message) {
                showToast(getString(R.string.share_failed));
            }
        });
    }

    private void launchGameReview() {
        CharSequence title = getString(R.string.button_game_review);
        CharSequence[] items = new CharSequence[]{getString(R.string.custom), getString(R.string.in_app_review)};
        showSelectorDialog(title, items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    launchGameCustomReview();
                } else if (which == 1) {
                    launchInAppReview();
                }
            }
        });
    }

    private void launchGameCustomReview() {
        View view = getLayoutInflater().inflate(R.layout.layout_custom_review, null, false);
        RatingBar ratingBar = view.findViewById(R.id.rating_bar);
        EditText editText = view.findViewById(R.id.edit_text);
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.button_game_review))
                .setView(view)
                .setNegativeButton(getString(android.R.string.cancel), null)
                .setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        float score = ratingBar.getRating();
                        String comment = editText.getText().toString();
                        SFPlatform.getInstance().launchGameCustomReview(score, comment, null);
                    }
                })
                .setCancelable(false)
                .create()
                .show();
    }

    private void launchInAppReview() {
        SFPlatform.getInstance().launchInAppReview(MainActivity.this, null);
    }

    private void queryLocaleCurrency() {
        SFPlatform.getInstance().setLocaleCurrencyListener(new SFLocaleCurrencyListener() {
            @Override
            public void onLocaleCurrency(List<SFProductDetails> productPrices) {
                StringBuilder builder = new StringBuilder();
                if (productPrices != null && !productPrices.isEmpty()) {
                    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
                    for (int i = 0; i < productPrices.size(); i++) {
                        SFProductDetails productPrice = productPrices.get(i);
                        Currency currency = Currency.getInstance(productPrice.getCurrency());
                        currencyFormat.setCurrency(currency);
                        builder.append("\n");
                        builder.append(productPrice.getProductId());
                        builder.append(": ");
                        builder.append(currencyFormat.format(productPrice.getPrice()));
                    }
                }
                showMessageDialog(getString(R.string.button_locale_currency), builder.toString());
            }
        });
    }

    private void getFirebaseToken() {
        SFPlatform.getInstance().setFirebaseMessagingListener(new SFFirebaseMessagingListener() {
            @Override
            public void onFirebaseToken(@NonNull String token) {
                showMessageDialog(getString(R.string.button_firebase_token), token);
            }

            @Override
            public void onMessageReceived(@NonNull SFFirebaseMessage message) {
                showToast("Firebase message received");
                if (message.hasNotification()) {
                    message.showNotification(getApplicationContext());
                } else {
                    showMessageDialog("Firebase message", message.getData().toString());
                }
            }
        });
    }

    private void trackEvent() {
        CharSequence title = getString(R.string.button_track_event);
        CharSequence[] items = new CharSequence[]{"All", "Firebase", "AppsFlyer"};
        showSelectorDialog(title, items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("analytics_type", items[which]);
                switch (which) {
                    case 0:
                        SFPlatform.getInstance().trackEvent(TEST_EVENT, params);
                        break;
                    case 1:
                        SFPlatform.getInstance().trackEvent(AnalyticsType.Firebase, TEST_EVENT, params);
                        break;
                    case 2:
                        SFPlatform.getInstance().trackEvent(AnalyticsType.AppsFlyer, "Total_Wins_0", params);
                        break;
                }
            }
        });
    }

    private void logout() {
        SFPlatform.getInstance().logout(this);
    }

    private void deleteAccount() {
        SFPlatform.getInstance().deleteAccount(this);
    }

    private void testCrash() {
        showToast("请查看Firebase控制台Crashlytics");
        throw new RuntimeException("Test Crash"); // Force a crash
    }

    private void switchIcon() {
        PackageManager packageManager = getPackageManager();
        if (componentNames == null) {
            componentNames = new ArrayList<>();
            componentNames.add(new ComponentName(this, "com.sf.sdk.demo.SplashActivity"));
            componentNames.add(new ComponentName(this, "com.sf.sdk.demo.SplashAlias"));
            for (ComponentName componentName : componentNames) {
                int componentEnabledSetting = packageManager.getComponentEnabledSetting(componentName);
                if (componentEnabledSetting == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                    this.componentName = componentName;
                    break;
                }
            }
        }
        int index = componentNames.indexOf(componentName);
        int enableIndex = (index == componentNames.size() - 1) ? 0 : index + 1;
        for (int i = 0; i < componentNames.size(); i++) {
            ComponentName componentName = componentNames.get(i);
            if (i == enableIndex) {
                this.componentName = componentName;
                packageManager.setComponentEnabledSetting(componentName,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                        PackageManager.DONT_KILL_APP);
            } else {
                packageManager.setComponentEnabledSetting(componentName,
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);
            }
        }
    }

    private void showMessageDialog(CharSequence title, CharSequence message) {
        showMessageDialog(title, message, null);
    }

    private void showMessageDialog(CharSequence title, CharSequence message, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setNegativeButton(getString(android.R.string.ok), listener)
                .create()
                .show();
    }

    private void showSelectorDialog(CharSequence title, CharSequence[] items, final DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setItems(items, listener)
                .setNegativeButton(getString(android.R.string.cancel), null)
                .create()
                .show();
    }

    private void showToast(String message) {
        if (!TextUtils.isEmpty(message)) {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SFPlatform.getInstance().destroy();
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("PackageManagerGetSignatures")
    private void generateKeyHash(Context context) {
        try {
            String packageName = context.getPackageName();
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            Signature[] signatures = packageInfo.signatures;
            if (signatures != null && signatures.length > 0) {
                for (Signature signature : signatures) {
                    MessageDigest digest = MessageDigest.getInstance("SHA-1");
                    digest.update(signature.toByteArray());
                    String keyHash = Base64.encodeToString(digest.digest(), Base64.DEFAULT);
                    System.out.println("KeyHash ==> " + keyHash);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean copyText(String text) {
        try {
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipboardManager != null) {
                clipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
