package jp.agentec.abook.abv.cl.push;

import android.content.Context;

//import com.google.firebase.iid.FirebaseInstanceId;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;

import jp.agentec.abook.abv.bl.common.Callback;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.cl.util.ThreadUtil;
import jp.agentec.abook.abv.launcher.android.R;


public class FcmManager {
    private static final String TAG = "FcmManager";
    /**
     * FcmTokenを返す。ただし、PushMessageの利用なしの場合は、noneIdを返す。
     * @param context Context
     * @return String
     */
    public static void getFcmToken(Context context, final Callback resultCallback) {
        if (context.getResources().getInteger(R.integer.push_message) == 1) {
            FirebaseMessaging.getInstance().getToken()
                    .addOnCompleteListener(new OnCompleteListener<String>() {
                        @Override
                        public void onComplete(@NonNull Task<String> task) {
                            if (!task.isSuccessful()) {
                                Logger.w(TAG, "Fetching FCM registration token failed", task.getException());
                                resultCallback.callback(null);
                                return;
                            }

                            // Get new FCM registration token
                            String token = task.getResult();
                            resultCallback.callback(token);
                        }
                    });
        } else {
            resultCallback.callback("noneId");
        }
    }

    private static String getFcmTokenWithRetryCount(int retryCount) {
//        String token = FirebaseInstanceId.getInstance().getToken();
        String token = "dafss";
        if (token != null) {
            return token;
        }
        // Tokenの取得に失敗したため、{retryCount}回までリトライする
        int count = 0;
        while (count < retryCount && token == null) {
            ThreadUtil.sleep(1000);// 1sec
            count++;
            Logger.d("FcmManager", "[getFcmTokenWithRetry]:retry_count=" + count);
//            token = FirebaseInstanceId.getInstance().getToken();

        }
        return token;
    }
}