@file:Suppress("DEPRECATED_IDENTITY_EQUALS", "KotlinConstantConditions")

package com.base.filerecoveryrecyclebin.fcm

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Icon
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat
import com.base.filerecoveryrecyclebin.MyApplication
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.activity.SplashActivity
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_APP_MANAGER
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_APP_PROCESS
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_BATTERY_INFO
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_JUNK_CLEAN_PUSH
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_RECOVERY_DOCUMENTS
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_RECOVERY_PHOTOS
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_RECOVERY_VIDEOS
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_SCREENSHOT_CLEAN
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_SIMILAR_IMAGE
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_WHATSAPP
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.AppProcessStringManager
import com.base.filerecoveryrecyclebin.utils.CleanJunkStringResourceManager
import com.base.filerecoveryrecyclebin.utils.DocumentRecoveryStringManager
import com.base.filerecoveryrecyclebin.utils.DuplicatePhotoStringResourceManager
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.utils.PhotoRecoveryStringManager
import com.base.filerecoveryrecyclebin.utils.ScreenshotCleanupStringManager
import com.base.filerecoveryrecyclebin.utils.VideoRecoveryStringManager
import com.base.filerecoveryrecyclebin.utils.WhatsappCleanerStringManager
import java.util.Random

/**
 * 构建发送通知
 * 用的actionId代替notificationId使用
 */
object NotificationUtil {

    private const val CHANNEL_ID = "recovery_notification_id" // 通知渠道ID
    private const val CHANNEL_NAME = "recovery_fcm_channel" // 通知渠道名称

    fun sendNotification(context: Context, actionId: Int) {
        val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_common)
        val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_common_small)

        var icon = 0
        var desc = ""
        var btn = ""
        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                icon = R.mipmap.cleanjunk_ss
                desc = CleanJunkStringResourceManager.getNextStringResource()
                btn = "Clean Up Space"
            }

            ID_SIMILAR_IMAGE -> {
                icon = R.mipmap.h_similar
                desc = DuplicatePhotoStringResourceManager.getNextCopy()
                btn = "Clean up"
            }

            ID_SCREENSHOT_CLEAN -> {
                icon = R.mipmap.repeatedphotos
                desc = ScreenshotCleanupStringManager.getNextCleanupCopy()
                btn = "Remove Screenshots"
            }

            ID_RECOVERY_PHOTOS -> {
                icon = R.mipmap.photos_ss
                desc = PhotoRecoveryStringManager.getNextRecoveryCopy()
                btn = "Retrieve Photo"
            }

            ID_RECOVERY_VIDEOS -> {
                icon = R.mipmap.videos_ss
                desc = VideoRecoveryStringManager.getNextRecoveryCopy()
                btn = "Recover Video"
            }

            ID_RECOVERY_DOCUMENTS -> {
                icon = R.mipmap.documents_ss
                desc = DocumentRecoveryStringManager.getNextRecoveryCopy()
                btn = "Restore Document"
            }

            ID_WHATSAPP -> {
                icon = R.mipmap.h_whatsapp
                desc = WhatsappCleanerStringManager.getNextCleanerCopy()
                btn = "WhatsApp Cleaner"
            }

            ID_APP_PROCESS -> {
                icon = R.mipmap.h_process
                desc = AppProcessStringManager.getNextDesc()
                btn = "WhatsApp Cleaner"
            }
        }
        bigRemoteViews.setImageViewResource(R.id.iv_icon, icon)
        bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
        bigRemoteViews.setTextViewText(R.id.tv_btn, btn)

        smallRemoteViews.setImageViewResource(R.id.iv_icon, icon)
        smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
        smallRemoteViews.setTextViewText(R.id.tv_btn, btn)

        //取消按钮
        bigRemoteViews.setOnClickPendingIntent(R.id.fl_cancel, cancelNotificationPendingIntent(context, actionId))

        //跳转
        val intent = Intent(context, SplashActivity::class.java)
        intent.putExtra("actionId", actionId)
        val btnRequestCode = Random().nextInt(1000)
        val btnPendingIntent = PendingIntent.getActivity(context, btnRequestCode, intent, PendingIntent.FLAG_IMMUTABLE)
        bigRemoteViews.setOnClickPendingIntent(R.id.fl_btn, btnPendingIntent)
        smallRemoteViews.setOnClickPendingIntent(R.id.tv_btn, btnPendingIntent)


        //构建发送通知
        sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
    }

    private fun cancelNotificationPendingIntent(context: Context, actionId: Int): PendingIntent {
        val cancelIntent = Intent(context, CloseNotificationReceiver::class.java)
        cancelIntent.setAction(CloseNotificationReceiver.Action)
        cancelIntent.putExtra(CloseNotificationReceiver.NotificationId, actionId)
        val broadcastRequestCode = Random().nextInt(1000)
        return PendingIntent.getBroadcast(context, broadcastRequestCode, cancelIntent, PendingIntent.FLAG_IMMUTABLE)
    }


    private fun sendCustomNotification(
        context: Context,
        actionId: Int,
        intent: Intent,
        bigRemoteViews: RemoteViews,
        smallRemoteViews: RemoteViews
    ) {

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        //创建channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH
            )
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            notificationManager.createNotificationChannel(channel)
        }


        // Create the notification
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, CHANNEL_ID)

        //设置状态栏内的小图标
        val smallIcon = IconCompat.createFromIcon(
            context, Icon.createWithResource(
                context, R.drawable.icon_100
            )
        )
        smallIcon?.let {
            builder.setSmallIcon(smallIcon)
        }
        builder.setContentTitle(context.resources.getString(R.string.app_name))
            .setContentText("notification")

        val requestCode = kotlin.random.Random.nextInt(1000)
        val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE)
        builder.setContentIntent(pendingIntent)
            .setDeleteIntent(cancelNotificationPendingIntent(context, actionId))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setAutoCancel(true)


        var small: RemoteViews? = bigRemoteViews
        //Android 12以下需要适配小RemoteViews
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            small = smallRemoteViews
        }
        builder.setContent(small)
        builder.setCustomHeadsUpContentView(small)
        builder.setCustomContentView(small)
        builder.setCustomBigContentView(bigRemoteViews)

        // Show the notification
        if (AppPreferences.getInstance().getString("actionS", "1").toInt() == 1) {
            notificationManager.notify(intent.getIntExtra("actionId", actionId), builder.build())
        } else {
            notificationManager.notify(actionId, builder.build())
        }
        AppPreferences.getInstance().put("last_notification_time", System.currentTimeMillis())
    }


    private var handlerThread: HandlerThread? = null
    private var handler: Handler? = null

    fun sendNotification(context: Context, where: String = "") {
        val actionId: Int = getNextNotificationId()
        EventUtils.event("showNotification", where, null, false)

        if (MyApplication.PAUSED_VALUE == 1) {
            return
        }

        val interval: Int = AppPreferences.getInstance().getString("notificationInterval", "60").toIntOrNull() ?: 60
        val lastTime: Long = AppPreferences.getInstance().getLong("last_notification_time", 0)
        val nowTime = System.currentTimeMillis()
        val x = nowTime - lastTime
        if (x < (interval * 1000)) {
            return
        }

        sendNotification(context, actionId)

        val open: Int = AppPreferences.getInstance().getString("open", "0").toIntOrNull() ?: 0

        if (open == 1) {
            val num: Int = AppPreferences.getInstance().getString("num", "0").toIntOrNull() ?: 0
            val delay: Long = AppPreferences.getInstance().getString("delay", "0").toLongOrNull() ?: 0L
            handlerThread = HandlerThread("NotificationHandlerThread")
            handlerThread!!.start()

            // 创建 Handler
            handler = Handler(handlerThread!!.looper)
            for (i in 1..num) {
                val time = i * delay
                handler?.postDelayed(Runnable {
                    if (MyApplication.PAUSED_VALUE === 1) {
                        handler?.removeCallbacksAndMessages(null)
                        return@Runnable
                    }
                    if (MyApplication.PAUSED_VALUE !== 1 && ScreenStatusReceiver.isDeviceInteractive() && !ScreenStatusReceiver.isSecureLockActive()) {
                        sendNotification(context, actionId)
                    }
                }, time)
            }
        }
    }


    fun stopNotificationHandler() {
        // 停止 HandlerThread
        if (handler != null) {
            handler?.removeCallbacksAndMessages(null)
        }
        if (handlerThread != null) {
            handlerThread?.quit()
            handlerThread = null
        }
        handler = null
    }

    private var currentNotificationIdIndex = -1

    private fun getNextNotificationId(): Int {
        // 将当前通知 ID 索引加 1
        currentNotificationIdIndex++

        // 如果当前通知 ID 索引超出列表范围，则将其重置为 0
        if (currentNotificationIdIndex >= NOTIFICATION_IDS.size) {
            currentNotificationIdIndex = 0
        }

        // 返回下一个通知 ID
        return NOTIFICATION_IDS[currentNotificationIdIndex]
    }

    private val NOTIFICATION_IDS = intArrayOf(
        ID_JUNK_CLEAN_PUSH,
        ID_SIMILAR_IMAGE,
        ID_SCREENSHOT_CLEAN,
        ID_RECOVERY_PHOTOS,
        ID_RECOVERY_VIDEOS,
        ID_RECOVERY_DOCUMENTS,
        ID_WHATSAPP,
        ID_APP_PROCESS,
        ID_APP_MANAGER,
        ID_BATTERY_INFO,
    )
}