package com.base.filerecoveryrecyclebin.fcm;

import androidx.annotation.NonNull;

import com.base.filerecoveryrecyclebin.MyApplication;
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils;
import com.base.filerecoveryrecyclebin.utils.AppPreferences;
import com.base.filerecoveryrecyclebin.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());

        AdDisplayUtils.getInstance().saveSp();
        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);
    }

}