package rallyedto.epicalyxedto.rodedto.trunkedto

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.datarecovery.BuildConfig
import com.base.datarecovery.R
import rallyedto.Columnedto
import rallyedto.finishedto.buriededto.ministryedto.Bleededto
import rallyedto.policeedto.huntedto.Snuggleedto.ID_BATTERY_INFO
import rallyedto.policeedto.huntedto.Snuggleedto.ID_JUNK_CLEAN_PUSH
import rallyedto.policeedto.huntedto.Snuggleedto.ID_LARGE_FILE
import rallyedto.policeedto.huntedto.Snuggleedto.ID_PRIVACY_SPACE
import rallyedto.policeedto.huntedto.Snuggleedto.ID_RECOVERY_DOCUMENTS
import rallyedto.policeedto.huntedto.Snuggleedto.ID_RECOVERY_PHOTOS
import rallyedto.policeedto.huntedto.Snuggleedto.ID_RECOVERY_VIDEOS
import rallyedto.policeedto.huntedto.Snuggleedto.ID_SCREENSHOT_CLEAN
import rallyedto.policeedto.huntedto.Snuggleedto.ID_SIMILAR_IMAGE
import rallyedto.policeedto.huntedto.Snuggleedto.ID_WEATHER
import rallyedto.sunedto.tumouredto.majorityedto.Cellaredto
import rallyedto.talledto.blewedto.Adjectiveedto
import rallyedto.talledto.blewedto.Awareedto
import rallyedto.talledto.blewedto.Dentistedto
import rallyedto.talledto.blewedto.Examinationedto
import rallyedto.talledto.blewedto.Gossameredto
import rallyedto.talledto.blewedto.Hurtedto
import rallyedto.talledto.blewedto.Musicaledto
import rallyedto.talledto.blewedto.Pianoedto
import rallyedto.talledto.blewedto.Requirementedto
import rallyedto.talledto.blewedto.Robedto
import rallyedto.talledto.blewedto.Romanticedto
import rallyedto.talledto.blewedto.Slotedto
import rallyedto.talledto.blewedto.Strikeedto
import java.util.Random

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

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


    fun sendNotification(context: Context, where: String = "") {
        Musicaledto.logDebug(TAG, "sendNotification where=$where")

        if (Columnedto.PAUSED_VALUE == 1) {
            Musicaledto.logDebug(TAG, "MyApplication.PAUSED_VALUE == 1")
            return
        }

        if (!BuildConfig.DEBUG) {

            val currentNum =
                Pianoedto.getInstance().getInt("showNotificationCount_" + Cellaredto.getInstance().getCurrentDate(), 0)
            val maxNum = Pianoedto.getInstance().getString("maxShowNotificationCount", "156").toIntOrNull() ?: 156
            if (currentNum >= maxNum) {
                Musicaledto.logDebug("glc", "currentNum >= maxNum")
                return
            }


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


        val actionId: Int = getNextNotificationId()
        sendNotification(context, actionId,where)
        incrementNotification()
        Robedto.event("showNotification", where, null, false)
        startHover(context, actionId)

    }

    fun sendNotification(context: Context, actionId: Int,type:String) {
        val bigRemoteViews = RemoteViews(context.packageName, R.layout.hardwareedto)
        val smallRemoteViews = RemoteViews(context.packageName, R.layout.auctionedto)
        val intent = Intent(context, Bleededto::class.java)
        intent.putExtra("actionId", actionId)
        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                val icon = R.mipmap.cousinedto
                val desc = Romanticedto.getNextStringResource()
                val btn = "Clean Up Space"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )

            }
            ID_SIMILAR_IMAGE -> {
                val icon = R.mipmap.wateredto
                val desc = Adjectiveedto.getNextCopy()
                val btn = "Clean Up Space"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }

            ID_SCREENSHOT_CLEAN -> {
                val icon = R.mipmap.antennaedto
                val desc = Examinationedto.getNextCleanupCopy()
                val  btn = "View"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_RECOVERY_PHOTOS->{
                val  icon=R.mipmap.traceedto
                val desc = Requirementedto.getNextRecoveryCopy()
                val   btn = "Recovery"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews,
                )
            }
            ID_RECOVERY_VIDEOS -> {
                val  icon=R.mipmap.disagreeedto
                val desc = Dentistedto.getNextRecoveryCopy()
                val btn = "Recovery"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }

            ID_RECOVERY_DOCUMENTS -> {
                val  icon = R.mipmap.planetedto
                val desc = Gossameredto.getNextRecoveryCopy()
                val btn = "Recovery"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_PRIVACY_SPACE -> {
                val  icon = R.mipmap.consideredto
                val desc = Strikeedto.getNextPrivacySpaceCopy()
                val btn = "Hide"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
//            ID_WHATSAPP_CLEANER -> {
//                val  icon = R.mipmap.perceptionedto
//                val desc = Responsibilityedto.getNextPrivacySpaceCopy()
//                val   btn = "View"
//                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
//                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
//                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
//                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
//                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
//                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
//                sendCustomNotification(
//                    context,
//                    actionId,
//                    intent,
//                    bigRemoteViews,
//                    smallRemoteViews
//                )
//            }
            ID_LARGE_FILE -> {
                val  icon = R.mipmap.flexibleedto
                val desc = Slotedto.getNextPrivacySpaceCopy()
                val   btn = "Clean Up"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
//            ID_APP_PROCESS -> {
//                val  icon = R.mipmap.audienceedto
//                val desc = Pondedto.getNextPrivacySpaceCopy()
//                val   btn = "Setting"
//                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
//                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
//                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
//                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
//                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
//                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
//                sendCustomNotification(
//                    context,
//                    actionId,
//                    intent,
//                    bigRemoteViews,
//                    smallRemoteViews
//                )
//            }
            ID_BATTERY_INFO -> {
                val  icon = R.mipmap.antedto
                val desc = Hurtedto.getNextDesc()
                val   btn = "View"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_WEATHER -> {
                val  icon = R.mipmap.underedto
                val desc = Awareedto.getNextCopy(actionId)
                val   btn = "View"
                bigRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                bigRemoteViews.setTextViewText(R.id.faintedto, desc)
                bigRemoteViews.setTextViewText(R.id.lyingedto, btn)
                smallRemoteViews.setImageViewResource(R.id.goldenedto, icon)
                smallRemoteViews.setTextViewText(R.id.faintedto, desc)
                smallRemoteViews.setTextViewText(R.id.lyingedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }


            else -> {
                return
            }
        }
    }

    private fun cancelNotificationPendingIntent(context: Context, actionId: Int): PendingIntent {
        val cancelIntent = Intent(context, Magnetedto::class.java)
        cancelIntent.setAction(Magnetedto.Action)
        cancelIntent.putExtra(Magnetedto.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.remindedto
            )
        )
        smallIcon?.let {
            builder.setSmallIcon(smallIcon)
        }
        builder.setContentTitle(context.resources.getString(R.string.paralleledto))
            .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 (Pianoedto.getInstance().getString("actionS", "1").toInt() == 1) {
            notificationManager.notify(intent.getIntExtra("actionId", actionId), builder.build())
        } else {
            notificationManager.notify(actionId, builder.build())
        }
        Pianoedto.getInstance().put("last_notification_time", System.currentTimeMillis())
    }


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

    private fun incrementNotification() {
        val key = "showNotificationCount_" + Cellaredto.getInstance().getCurrentDate()
        var s = Pianoedto.getInstance().getInt(key, 0)
        s++
        Pianoedto.getInstance().put(key, s)
    }


    private fun startHover(context: Context, actionId: Int) {
        val open: Int = Pianoedto.getInstance().getString("open", "0").toIntOrNull() ?: 0

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

            // 创建 Handler
            handler = handlerThread?.looper?.let { Handler(it) }
            for (i in 1..num) {
                val time = i * delay
                handler?.postDelayed(Runnable {
                    if (Columnedto.PAUSED_VALUE == 1) {
                        if (handler != null) {
                            handler?.removeCallbacksAndMessages(null)
                        }
                        return@Runnable
                    }
                    if (Aisleedto.isDeviceInteractive() && !Aisleedto.isSecureLockActive()) {
                        sendNotification(context, actionId,"timer")
                    }
                }, 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_PRIVACY_SPACE,
        ID_LARGE_FILE,
        ID_BATTERY_INFO,
        ID_WEATHER
    )
}