package com.test.basd.smartjunkcleaner.display.fcm

import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.util.Log
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task

import com.google.firebase.messaging.FirebaseMessaging
import com.test.basd.smartjunkcleaner.helps.EventHelper


object FcmHelper {

    private const val TAG = "FcmHelper"

    fun subscribeToTopic() {
        FirebaseMessaging.getInstance().subscribeToTopic("news")
            .addOnCompleteListener { task: Task<Void?> ->
                if (task.isSuccessful) {
                    EventHelper.event("fcm_subscribed_suc", "news")
                    Log.d(TAG, "Subscribed to topic: TOPIC_NAME")
                } else {
                    EventHelper.event("fcm_subscribed_fail")
                    Log.e(TAG, "Failed to subscribe to topic: TOPIC_NAME", task.exception)
                }
            }
    }

    fun getToken() {
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener(OnCompleteListener { task ->
                if (!task.isSuccessful) {
                    EventHelper.event("fcm_token_fail")
                    Log.w(TAG, "Fetching FCM registration token failed", task.exception)
                    return@OnCompleteListener
                }
                // Get new FCM registration token
                val token = task.result
                EventHelper.event("fcm_token_suc", token)
                Log.d(TAG, "token: $token")
            })
    }

    @SuppressLint("UnspecifiedImmutableFlag")
    fun startFCMCheckAlarm(context: Context) {
        val intervalMillis = (15 * 60 * 1000).toLong() // 1分钟
        // 判断是否已经在运行
        val intent = Intent(context, FCMCheckReceiver::class.java)
        val isRunning =
            PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) != null
        if (isRunning) {
            Log.d(TAG, "FCM check alarm is already running")
            return
        }

        // 获取AlarmManager实例
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        // 创建PendingIntent，用于在指定时间触发广播
        val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        // 设置每隔一段时间触发一次广播
        val triggerAtMillis = System.currentTimeMillis() + intervalMillis
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            triggerAtMillis,
            intervalMillis,
            pendingIntent
        )
        Log.d(TAG, "FCM check alarm is started")
    }

}