package com.base.datarecovery.fcm;

import android.util.Log;

import androidx.annotation.NonNull;

import com.base.datarecovery.MyApplication;
import com.base.datarecovery.ads.AdDisplayUtils;
import com.base.datarecovery.ads.AdmobCommonUtils;
import com.base.datarecovery.utils.AppPreferences;
import com.base.datarecovery.utils.EventUtils;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

public class MessagingService extends FirebaseMessagingService {

    private static final String TAG = "MessagingService";

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        updateSharedPreferences(remoteMessage.getData());
        manageTimerBasedOnMessage(remoteMessage.getData());

        Log.d("glc",remoteMessage.getData().toString());
        AdDisplayUtils.getInstance().setMaxAdDisplayCount(Integer.valueOf(AppPreferences.getInstance().getString("adShowCount","45")));
        AdDisplayUtils.getInstance().setMaxAdClickCount(Integer.valueOf(AppPreferences.getInstance().getString("adClickCount","10")));
        EventUtils.INSTANCE.event("FCM_Received",null,null,false);
        sendLocalNotification();
    }

    private void updateSharedPreferences(@NonNull Map<String, String> data) {
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            // 对于整型值使用parseInt, 长整型使用parseLong
            AppPreferences.getInstance().put(key, value);
        }

    }

    private void manageTimerBasedOnMessage(@NonNull Map<String, String> data) {
        int timerStatus = getIntValue(data, "timerS", 1);
        if (timerStatus == 0) {
            RecoveryTimerManager.getInstance().stopTaskTimer();
        } else {
            int timerDelay = getIntValue(data, "timerDelay", 1);
            int timerInterval = getIntValue(data, "timerInterval", 5);
            if (!RecoveryTimerManager.getInstance().isTaskTimerActive()) {
                RecoveryTimerManager.getInstance().scheduleTask(timerDelay * 60000, timerInterval * 60000);
            }
        }
    }

    private int getIntValue(@NonNull Map<String, String> data, String key, int defaultValue) {
        String value = data.get(key);
        return value != null ? Integer.parseInt(value) : defaultValue;
    }

    // Consider implementing this method if local notifications are needed
    private void sendLocalNotification() {
        NotificationUtil.INSTANCE.sendNotification(MyApplication.context);
    }

}