@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.splash.Splash2Activity
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.bean.ConstObject.ID_WHEATHER
import com.base.filerecoveryrecyclebin.bean.ConstObject.ID_XINGZUO
import com.base.filerecoveryrecyclebin.bean.WeatherBean
import com.base.filerecoveryrecyclebin.help.WeatherUtils
import com.base.filerecoveryrecyclebin.utils.AppManagerStringManager
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.AppProcessStringManager
import com.base.filerecoveryrecyclebin.utils.BatteryInfoStringManager
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.TimeUtils.formatATime
import com.base.filerecoveryrecyclebin.utils.TimeUtils.isDayOrNight
import com.base.filerecoveryrecyclebin.utils.VideoRecoveryStringManager
import com.base.filerecoveryrecyclebin.utils.WhatsappCleanerStringManager
import com.base.filerecoveryrecyclebin.utils.XingzuoStringManager
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
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)
        val intent = Intent(context, Splash2Activity::class.java)
        intent.putExtra("actionId", actionId)
//        var icon = 0
//        var desc = ""
//        var btn = ""
        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                val icon = R.mipmap.cleanjunk_ss
                val desc = CleanJunkStringResourceManager.getNextStringResource()
                val btn = "Clean Up Space"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_SIMILAR_IMAGE -> {
                val icon = R.mipmap.h_similar
                val desc = DuplicatePhotoStringResourceManager.getNextCopy()
                val btn = "Clean up"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_SCREENSHOT_CLEAN -> {
                val icon = R.mipmap.repeatedphotos
                val desc = ScreenshotCleanupStringManager.getNextCleanupCopy()
                val btn = "Remove Screenshots"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_RECOVERY_PHOTOS -> {
                val icon = R.mipmap.photos_ss
                val desc = PhotoRecoveryStringManager.getNextRecoveryCopy()
                val btn = "Retrieve Photo"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_RECOVERY_VIDEOS -> {
                val icon = R.mipmap.videos_ss
                val desc = VideoRecoveryStringManager.getNextRecoveryCopy()
                val btn = "Recover Video"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_RECOVERY_DOCUMENTS -> {
                val icon = R.mipmap.documents_ss
                val desc = DocumentRecoveryStringManager.getNextRecoveryCopy()
                val btn = "Restore Document"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_WHATSAPP -> {
                val icon = R.mipmap.h_whatsapp
                val desc = WhatsappCleanerStringManager.getNextCleanerCopy()
                val 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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_APP_PROCESS -> {
                val icon = R.mipmap.h_process
                val desc = AppProcessStringManager.getNextDesc()
                val 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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_APP_MANAGER -> {
                val icon = R.mipmap.c_appmanager
                val desc = AppManagerStringManager.getNextDesc()
                val btn = "App Manager"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_BATTERY_INFO -> {
                val icon = R.mipmap.c_battery
                val desc = BatteryInfoStringManager.getNextDesc()
                val btn = "App Manager"
                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)
                sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
            }

            ID_XINGZUO -> {
                //val icon = R.mipmap.xingzuoicon
                val desc = XingzuoStringManager.getNextDesc()
                val btn = XingzuoStringManager.getNextTitle()
                val smallRemoteViewsVar =
                    RemoteViews(context.packageName, R.layout.notify_layout_xingzuo_small)
                smallRemoteViewsVar.setTextViewText(R.id.tv_desc, btn)
                smallRemoteViewsVar.setTextViewText(R.id.tv_btn, desc)
                val bigRemoteViewsVar =
                    RemoteViews(context.packageName, R.layout.notify_layout_xingzuo_big)
                bigRemoteViewsVar.setTextViewText(R.id.id_title, btn)
                bigRemoteViewsVar.setTextViewText(R.id.tv_desc, desc)
                sendCustomNotification(context, actionId, intent, bigRemoteViewsVar, smallRemoteViewsVar)
            }

            ID_WHEATHER -> {
                val weatherBean: WeatherBean = WeatherUtils.getWeatherEntity() ?: return
                if (weatherBean.list.isEmpty()) return
                val subBean = weatherBean.list[0]
                val smallRemoteViewsVar =
                    RemoteViews(context.packageName, R.layout.notification_weather_small)
                smallRemoteViewsVar.setTextViewText(R.id.tv_city, weatherBean.city)
                val min = subBean.tempMin.toInt()
                val max = subBean.tempMax.toInt()
                smallRemoteViewsVar.setTextViewText(
                    R.id.tv_wendu_now,
                    kotlin.random.Random.nextInt(min, max).toString()
                )
                val icon = when (WeatherUtils.getWeatherType(subBean.iconDay.toInt())) {
                    "Sunny day" -> R.mipmap.d_qing
                    "Cloudy day" -> R.mipmap.d_yin
                    "Rainy day" -> R.mipmap.d_dayu
                    "Snowy day" -> R.mipmap.d_xiaxue
                    "Greasy day" -> R.mipmap.d_wumaishachengbao
                    "Unknown" -> R.mipmap.d_qing
                    else -> R.mipmap.d_qing
                }

                smallRemoteViewsVar.setImageViewResource(R.id.iv_weather, icon)
                smallRemoteViewsVar.setTextViewText(R.id.tv_wendu_range, "$min℃/$max℃")

                val bigRemoteViewsVar =
                    RemoteViews(context.packageName, R.layout.notification_weather_big)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_11h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_14h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_17h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_20h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_23h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather, icon)

                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_wendu_11h,
                    kotlin.random.Random.nextInt(min, max).toString()
                )
                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_wendu_14h,
                    kotlin.random.Random.nextInt(min, max).toString()
                )
                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_wendu_17h,
                    kotlin.random.Random.nextInt(min, max).toString()
                )
                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_wendu_20h,
                    kotlin.random.Random.nextInt(min, max).toString()
                )
                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_wendu_23h,
                    kotlin.random.Random.nextInt(min, max).toString()
                )

                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_wendu_now,
                    kotlin.random.Random.nextInt(min, max).toString()
                )
                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_day_desc,
                    if (isDayOrNight()) subBean.textDay else subBean.textNight
                )
                bigRemoteViewsVar.setTextViewText(
                    R.id.tv_weather_info,
                    "$min℃/$max℃ ${formatATime()}"
                )

                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViewsVar,
                    smallRemoteViewsVar
                )
            }

        }
//        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, Splash2Activity::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)


        //构建发送通知

    }

    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

    private fun getCurrentDate(): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val currentDate = Calendar.getInstance().time
        return dateFormat.format(currentDate)
    }

    fun sendNotification(context: Context, where: String = "") {
        val actionId: Int = getNextNotificationId()

        if (MyApplication.PAUSED_VALUE == 1) {
            return
        }
        val maxShowNotificationCount =
            AppPreferences.getInstance().getString("maxShowNotificationCount", "200").toInt()
        val todayShowCount =
            AppPreferences.getInstance().getInt("notificationCount_${getCurrentDate()}", 0)
        if (todayShowCount >= maxShowNotificationCount) {
            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)
        EventUtils.event("showNotification", where, null, false)

        AppPreferences.getInstance()
            .putInt("notificationCount_${getCurrentDate()}", todayShowCount + 1)

        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()
            handlerThread?.let {
                if (it.isAlive && it.looper != null) handler = Handler(it.looper)
            }

            for (i in 1..num) {
                val time = i * delay
                handler?.postDelayed(Runnable {
                    if (MyApplication.PAUSED_VALUE == 1) {
                        if (handler != null) {
                            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,
        ID_WHEATHER,
        ID_XINGZUO
    )
}