package com.base.datarecovery.fcm;

import androidx.annotation.NonNull;

import com.base.datarecovery.MyApplication;
import com.base.datarecovery.ads.AdDisplayUtils;
import com.base.datarecovery.utils.AppPreferences;
import com.base.datarecovery.utils.EventUtils;
import com.base.datarecovery.utils.LogEx;
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());
        LogEx.INSTANCE.logDebug(TAG,"onMessageReceived",false);
        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);
    }

}