package rowedto.jockeyedto.sheetedto.interactiveedto.twistedto

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 rowedto.jockeyedto.sheetedto.Epicalyxedto
import rowedto.jockeyedto.sheetedto.atticedto.fadeedto.Bottomedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_APP_MANAGER
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_BATTERY_INFO
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_JUNK_CLEAN_PUSH
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_LARGE_FILE
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_PRIVACY_SPACE
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_RECOVERY_DOCUMENTS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_RECOVERY_PHOTOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_RECOVERY_VIDEOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_SCREENSHOT_CLEAN
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_SIMILAR_IMAGE
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_WEATHER
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ID_XINGZUO
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Abridgeedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Bazaaredto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Dishedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Fallenedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Instructionedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Introducededto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Layedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Loadedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Militaryedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Preachedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Slantedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spokespersonedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Stewardedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Vagueedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Welcomeedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Modestedto
import java.util.Random

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

    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 = "") {
        Dishedto.logDebug(TAG, "sendNotification where=$where")

        if (Epicalyxedto.PAUSED_VALUE == 1) {
            Dishedto.logDebug(TAG, "MyApplication.PAUSED_VALUE == 1")
            return
        }

        if (!BuildConfig.DEBUG) {

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


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


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

    }

    fun sendNotification(context: Context, actionId: Int,type:String) {
        val bigRemoteViews = RemoteViews(context.packageName, R.layout.contemptedto)
        val smallRemoteViews = RemoteViews(context.packageName, R.layout.teaseedto)
        val intent = Intent(context, Bottomedto::class.java)
        intent.putExtra("actionId", actionId)
        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                val icon = R.mipmap.cylinderedto
                val desc = Fallenedto.getNextStringResource()
                val btn = "Clean Up Space"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )

            }
            ID_SIMILAR_IMAGE -> {
                val icon = R.mipmap.borrowedto
                val desc = Bazaaredto.getNextCopy()
                val btn = "Clean Up Space"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }

            ID_SCREENSHOT_CLEAN -> {
                val icon = R.mipmap.shipedto
                val desc = Welcomeedto.getNextCleanupCopy()
                val  btn = "View"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_RECOVERY_PHOTOS->{
                val  icon=R.mipmap.bucketedto
                val desc = Instructionedto.getNextRecoveryCopy()
                val   btn = "Recovery"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews,
                )
            }
            ID_RECOVERY_VIDEOS -> {
                val  icon=R.mipmap.realismedto
                val desc = Loadedto.getNextRecoveryCopy()
                val btn = "Recovery"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }

            ID_RECOVERY_DOCUMENTS -> {
                val  icon = R.mipmap.weakedto
                val desc = Militaryedto.getNextRecoveryCopy()
                val btn = "Recovery"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_PRIVACY_SPACE -> {
                val  icon = R.mipmap.graphedto
                val desc = Vagueedto.getNextPrivacySpaceCopy()
                val btn = "Hide"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
//            ID_WHATSAPP_CLEANER -> {
//                val  icon = R.mipmap.deficitedto
//                val desc = Boomedto.getNextPrivacySpaceCopy()
//                val   btn = "View"
//                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
//                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
//                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
//                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
//                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
//                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
//                sendCustomNotification(
//                    context,
//                    actionId,
//                    intent,
//                    bigRemoteViews,
//                    smallRemoteViews
//                )
//            }
            ID_LARGE_FILE -> {
                val  icon = R.mipmap.rackedto
                val desc = Layedto.getNextPrivacySpaceCopy()
                val   btn = "Clean Up"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
//            ID_APP_PROCESS -> {
//                val  icon = R.mipmap.econoboxedto
//                val desc = Traveledto.getNextPrivacySpaceCopy()
//                val   btn = "Setting"
//                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
//                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
//                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
//                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
//                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
//                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
//                sendCustomNotification(
//                    context,
//                    actionId,
//                    intent,
//                    bigRemoteViews,
//                    smallRemoteViews
//                )
//            }
            ID_APP_MANAGER -> {
                val  icon = R.mipmap.patchedto
                val desc = Spokespersonedto.getNextDesc()
                val   btn = "Uninstall App"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_BATTERY_INFO -> {
                val  icon = R.mipmap.abuseedto
                val desc = Preachedto.getNextDesc()
                val   btn = "View"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_WEATHER -> {
                val  icon = R.mipmap.slightedto
                val desc = Abridgeedto.getNextCopy(actionId)
                val   btn = "View"
                bigRemoteViews.setImageViewResource(R.id.dashedto, icon)
                bigRemoteViews.setTextViewText(R.id.vatedto, desc)
                bigRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                smallRemoteViews.setImageViewResource(R.id.dashedto, icon)
                smallRemoteViews.setTextViewText(R.id.vatedto, desc)
                smallRemoteViews.setTextViewText(R.id.pledgeedto, btn)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViews,
                    smallRemoteViews
                )
            }
            ID_XINGZUO -> {
                //val icon = R.mipmap.xingzuoicon
                val desc = Introducededto.getNextDesc()
                val btn = Introducededto.getNextTitle()
                val smallRemoteViewsVar =
                    RemoteViews(context.packageName, R.layout.happilyedto)
                smallRemoteViewsVar.setTextViewText(R.id.vatedto, btn)
                smallRemoteViewsVar.setTextViewText(R.id.recordingedto, desc)
                val bigRemoteViewsVar =
                    RemoteViews(context.packageName, R.layout.favoredto)
                bigRemoteViewsVar.setTextViewText(R.id.banneredto, btn)
                bigRemoteViewsVar.setTextViewText(R.id.vatedto, desc)
                sendCustomNotification(
                    context,
                    actionId,
                    intent,
                    bigRemoteViewsVar,
                    smallRemoteViewsVar
                )
            }

            else -> {
                return
            }
        }
    }

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


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

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


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

        if (open == 1) {
            val num: Int = Stewardedto.getInstance().getString("num", "0").toIntOrNull() ?: 0
            val delay: Long =
                Stewardedto.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 (Epicalyxedto.PAUSED_VALUE == 1) {
                        if (handler != null) {
                            handler?.removeCallbacksAndMessages(null)
                        }
                        return@Runnable
                    }
                    if (Trouseredto.isDeviceInteractive() && !Trouseredto.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_APP_MANAGER,
        ID_BATTERY_INFO,
        ID_WEATHER,
        ID_XINGZUO
    )
}