package importantedto.growedto.umbrellaedto

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 importantedto.Exhibitionedto
import importantedto.admireedto.sweptedto.Monarchedto
import importantedto.appliededto.surgeonedto.promiseedto.dialectedto.Styleedto
import importantedto.concreteedto.cameedto.Hateedto.ID_APP_MANAGER
import importantedto.concreteedto.cameedto.Hateedto.ID_APP_PROCESS
import importantedto.concreteedto.cameedto.Hateedto.ID_BATTERY_INFO
import importantedto.concreteedto.cameedto.Hateedto.ID_JUNK_CLEAN_PUSH
import importantedto.concreteedto.cameedto.Hateedto.ID_LARGE_FILE
import importantedto.concreteedto.cameedto.Hateedto.ID_PRIVACY_SPACE
import importantedto.concreteedto.cameedto.Hateedto.ID_RECOVERY_DOCUMENTS
import importantedto.concreteedto.cameedto.Hateedto.ID_RECOVERY_PHOTOS
import importantedto.concreteedto.cameedto.Hateedto.ID_RECOVERY_VIDEOS
import importantedto.concreteedto.cameedto.Hateedto.ID_SCREENSHOT_CLEAN
import importantedto.concreteedto.cameedto.Hateedto.ID_SIMILAR_IMAGE
import importantedto.concreteedto.cameedto.Hateedto.ID_WHATSAPP_CLEANER
import importantedto.gallonedto.Arrowedto
import importantedto.gallonedto.Bitteredto
import importantedto.gallonedto.Digitaledto
import importantedto.gallonedto.Fileedto
import importantedto.gallonedto.Harvestedto
import importantedto.gallonedto.Myselfedto
import importantedto.gallonedto.Nightedto
import importantedto.gallonedto.Rideredto
import importantedto.gallonedto.Sayedto
import importantedto.gallonedto.Selectionedto
import importantedto.gallonedto.Slopeedto
import importantedto.gallonedto.Substituteedto
import importantedto.gallonedto.Tumbleedto
import importantedto.gallonedto.Waitedto
import importantedto.gallonedto.Wateredto
import java.util.Random

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

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

        if (Exhibitionedto.PAUSED_VALUE == 1) {
            Tumbleedto.logDebug(TAG, "MyApplication.PAUSED_VALUE == 1")
            return
        }

        if (!BuildConfig.DEBUG) {

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


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


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

    }

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

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

            ID_SIMILAR_IMAGE -> {
                icon = R.mipmap.guideedto
                desc = Arrowedto.getNextCopy()
                btn = "Clean Up Space"
            }

            ID_SCREENSHOT_CLEAN -> {
                icon = R.mipmap.liquidedto
                desc = Slopeedto.getNextCleanupCopy()
                btn = "Clean Up Space"
            }

            ID_RECOVERY_PHOTOS -> {
                icon = R.mipmap.hauntedto
                desc = Nightedto.getNextRecoveryCopy()
                btn = "Recovery"
            }

            ID_RECOVERY_VIDEOS -> {
                icon = R.mipmap.binedto
                desc = Harvestedto.getNextRecoveryCopy()
                btn = "Recovery"
            }

            ID_RECOVERY_DOCUMENTS -> {
                icon = R.mipmap.revolutionaryedto
                desc = Fileedto.getNextRecoveryCopy()
                btn = "Recovery"
            }

            ID_PRIVACY_SPACE -> {
                icon = R.mipmap.emotionedto
                desc = Substituteedto.getNextPrivacySpaceCopy()
                btn = "Hide"
            }

            ID_WHATSAPP_CLEANER -> {
                icon = R.mipmap.corruptionedto
                desc = Myselfedto.getNextPrivacySpaceCopy()
                btn = "Clean Up"
            }

            ID_LARGE_FILE -> {
                icon = R.mipmap.bookedto
                desc = Selectionedto.getNextPrivacySpaceCopy()
                btn = "Clean Up"
            }

            ID_APP_PROCESS -> {
                icon = R.mipmap.landscapeedto
                desc = Digitaledto.getNextPrivacySpaceCopy()
                btn = "Setting"
            }

            ID_APP_MANAGER -> {
                icon = R.mipmap.equipedto
                desc = Bitteredto.getNextDesc()
                btn = "App Manager"
            }

            ID_BATTERY_INFO -> {
                icon = R.mipmap.brandedto
                desc = Sayedto.getNextDesc()
                btn = "App Manager"
            }
        }
        bigRemoteViews.setImageViewResource(R.id.dueedto, icon)
        bigRemoteViews.setTextViewText(R.id.collegeedto, desc)
        bigRemoteViews.setTextViewText(R.id.trolleyedto, btn)

        smallRemoteViews.setImageViewResource(R.id.dueedto, icon)
        smallRemoteViews.setTextViewText(R.id.collegeedto, desc)
        smallRemoteViews.setTextViewText(R.id.trolleyedto, btn)

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

        //跳转
        val intent = Intent(context, Styleedto::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.didedto, btnPendingIntent)
        smallRemoteViews.setOnClickPendingIntent(R.id.trolleyedto, btnPendingIntent)


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

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


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

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


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

        if (open == 1) {
            val num: Int = Waitedto.getInstance().getString("num", "0").toIntOrNull() ?: 0
            val delay: Long =
                Waitedto.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 (Exhibitionedto.PAUSED_VALUE == 1) {
                        if (handler != null) {
                            handler?.removeCallbacksAndMessages(null)
                        }
                        return@Runnable
                    }
                    if (Exhibitionedto.PAUSED_VALUE != 1 && Wakeedto.isDeviceInteractive() && !Wakeedto.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_PRIVACY_SPACE,
        ID_WHATSAPP_CLEANER,
        ID_LARGE_FILE,
        ID_APP_PROCESS,
        ID_APP_MANAGER,
        ID_BATTERY_INFO,
    )
}