package com.zxhyis.toolss.common.notification

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_MUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.os.Build
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.ALL_LAST_PUSH_TIME
import com.zxhyis.toolss.ad.ComUtils
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.ad.bean.EventParams
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_APP_MANAGER
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_BATTERY_OPTIMIZATION
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_BATTERY_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_BIGFILE_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_CHARGE
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_CLEAN_NOTIFICATION
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_CLEAN_SPEAKER
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_INSTALL_PACKAGE_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_JUNK_CLEAN_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_LOW_BATTERY_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_LOW_RAM_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_NETWORK_TRAFFIC
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_PHONE_ACCELERATE
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_PHOTO_COMPRESS
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_RECENT_USE_APP
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_SIMILAR_IMAGE
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_UNINSTALL_PACKAGE_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_VIRUS_PUSH
import com.zxhyis.toolss.ad.createByActionId
import com.zxhyis.toolss.ad.queryDataStoreBlock
import com.zxhyis.toolss.ad.saveDataStoreBlock
import com.zxhyis.toolss.logic.LogEx
import com.zxhyis.toolss.ui.page.SplashActivity
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.internal.notify
import java.util.Timer
import kotlin.random.Random


/**
 * 推送的帮助类，定义了推送逻辑
 * 动态申请 <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
 */
object NotificationHelper {


    private const val CHANNEL_ID = "clean master notification"
    private const val CHANNEL_NAME = "clean master channel"
    private val TAG = "NotificationHelper"
    val notificationId = 12086


    /**
     * 当前APP支持的通知类型
     */
    val supportNotification = arrayListOf(
        ID_JUNK_CLEAN_PUSH,
        ID_VIRUS_PUSH,
        ID_BIGFILE_PUSH,
        ID_PHOTO_COMPRESS,
        ID_APP_MANAGER,
        ID_NETWORK_TRAFFIC,
        ID_CLEAN_NOTIFICATION,
        ID_RECENT_USE_APP,
        ID_SIMILAR_IMAGE,
        ID_CLEAN_SPEAKER,
        ID_BATTERY_OPTIMIZATION,
        ID_PHONE_ACCELERATE,//被动推送加入主动推送列表
    )

    /**
     * 轮训推送任务
     */
    fun pushCircleOrderTimber(eventParams: EventParams) {
        val pushManagement = ComUtils.getPushConfig()
        val interval = pushManagement.loop_interval
        LogEx.logDebug(TAG, "pushManagement=$pushManagement loop_interval=$interval")
        val timer = Timer()
        timer.schedule(NotificationTimerTask(eventParams), 0L, interval * 1000L)
    }

    /**
     * 过滤可推送actionId
     */
    fun filterAction(pushCircleOrder: List<Int>): ArrayList<Int> {
        //过滤已有功能
        val filterList = arrayListOf<Int>()
        pushCircleOrder.forEach { action ->
            if (supportNotification.contains(action)) {
                filterList.add(action)
            }
        }
        return filterList
    }

    /**
     * 获取当前的推送id
     */
    fun getPresentPushId(): Int {
        val pushCircleOrder = ComUtils.getPushConfig().push_circle_order
        LogEx.logDebug(TAG, "push_circle_order=$pushCircleOrder")
        val tempList = arrayListOf<Int>()

        val json =
            FileApp.fContext.queryDataStoreBlock(stringPreferencesKey("push_circle_order"), "")
        if ((json == "") or (json == "null")) {//初始化
            val filterList = filterAction(pushCircleOrder)
            val initJson = Gson().toJson(filterList)
            FileApp.fContext.saveDataStoreBlock(stringPreferencesKey("push_circle_order"), initJson)
            tempList.addAll(filterList)
        } else {
            val array = Gson().fromJson(json, object : TypeToken<Array<Int>>() {})
            tempList.addAll(array)

            if (tempList.isEmpty()) {
                val filterList = filterAction(pushCircleOrder)
                val saveJson = Gson().toJson(filterList)
                FileApp.fContext.saveDataStoreBlock(
                    stringPreferencesKey("push_circle_order"),
                    saveJson
                )
                tempList.addAll(filterList)
            }
        }

        val i = tempList[0]
        tempList.remove(i)

        val usedJson = Gson().toJson(tempList)
        FileApp.fContext.saveDataStoreBlock(stringPreferencesKey("push_circle_order"), usedJson)
        LogEx.logDebug(TAG, "i=$i tempList=$tempList pushCircleOrder=$pushCircleOrder")
        return i
    }

    /**
     * 发送通知对于
     * @param extra 额外参数
     */
    @SuppressLint("RemoteViewLayout")
    fun Context.postActionNotification(actionId: Int, eventParams: EventParams? = null, extra: Int? = null) {


        val remoteViews = RemoteViews(packageName, R.layout.notification_common)

        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.lajiqingli)
                remoteViews.setTextViewText(R.id.tv_desc, "Clean up remaining junk files")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_VIRUS_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.bingdu)
                remoteViews.setTextViewText(R.id.tv_desc, "Protect your device and privacy, scan for virus threats now!")
                remoteViews.setTextViewText(R.id.tv_btn, "Scan")
            }

            ID_BATTERY_OPTIMIZATION -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.dianchi_notifi)
                val random = Random.nextInt(0, 50)
                remoteViews.setTextViewText(R.id.tv_desc, "$random Apps are consuming photo power")
                remoteViews.setTextViewText(R.id.tv_btn, "Optimize")
            }

            ID_BIGFILE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.dawenjian_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "Clean big files to free up storage space")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_PHOTO_COMPRESS -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.yasuo)
                remoteViews.setTextViewText(R.id.tv_desc, "Compress images to release more space")
                remoteViews.setTextViewText(R.id.tv_btn, "Compress")
            }

            ID_APP_MANAGER -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.appmanager_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "Check apps size and uninstall junk apps to release storage space")
                remoteViews.setTextViewText(R.id.tv_btn, "Manage")
            }

            ID_NETWORK_TRAFFIC -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.liuliang)
                remoteViews.setTextViewText(R.id.tv_desc, "View network traffic usage and stop traffic-consuming apps.")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_CLEAN_NOTIFICATION -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.tongzhi_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "Too many annoying notifications? Block and clean")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_RECENT_USE_APP -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.zuijin_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "Check and manage recently active apps")
                remoteViews.setTextViewText(R.id.tv_btn, "Manage")
            }

            ID_SIMILAR_IMAGE -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.xiangsi_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "Check similar photos to release more space")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_CLEAN_SPEAKER -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.yangshenqi)
                remoteViews.setTextViewText(R.id.tv_desc, "Clean the speaker dust and fix the low volume problem")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

//==================================下面是被动推送的情况===============================================

            ID_INSTALL_PACKAGE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.anzhuang_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "Install successfully, scan for virus threats now!")
                remoteViews.setTextViewText(R.id.tv_btn, "Scan")
            }

            ID_UNINSTALL_PACKAGE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.xiezai_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "Uninstalled successfully, clean residual files from your device")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_CHARGE -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.chongdian_notifi)
                remoteViews.setTextViewText(R.id.tv_desc, "View phone battery consumption recently")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_LOW_BATTERY_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.dianliangdi)
                remoteViews.setTextViewText(R.id.tv_desc, "The battery is $extra%, view the battery information")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_PHONE_ACCELERATE -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.neicundi)
                remoteViews.setTextViewText(R.id.tv_desc, "Ram usage  reached $extra%, optimize now!")
                remoteViews.setTextViewText(R.id.tv_btn, "Optimize")
            }

            else -> {
                return
            }
        }

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) FLAG_MUTABLE else FLAG_UPDATE_CURRENT


        //cancel事件
        val cancelIntent = Intent(NotificationBroadcast.action).apply {
            putExtra("cancel", "cancel")
        }
        val cancelRequestCode = Random.nextInt(0, 1000)
        val cancelPendingIntent = PendingIntent.getBroadcast(FileApp.fContext, cancelRequestCode, cancelIntent, flag)
        remoteViews.setOnClickPendingIntent(R.id.fl_cancel, cancelPendingIntent)

        val intent = Intent(applicationContext, SplashActivity::class.java)
        val title: String = ""
        val desc: String = ""
        intent.putExtra("title", title)
        intent.putExtra("desc", desc)
        val customKey = "type"
        intent.putExtra(customKey, actionId)


        //按钮事件
        val btnRequestCode = Random.nextInt(0, 1000)
        val btnPendingIntent = PendingIntent.getActivity(FileApp.fContext, btnRequestCode, intent, flag)
        remoteViews.setOnClickPendingIntent(R.id.fl_btn, btnPendingIntent)

        //每种类型保存值
        FileApp.fContext.saveDataStoreBlock(createByActionId(actionId), System.currentTimeMillis())
        //大间隔所需值
        FileApp.fContext.saveDataStoreBlock(ALL_LAST_PUSH_TIME, System.currentTimeMillis())
        EventHelper.event(
            "pushCircleOrder_showNotification",
            "actionId=$actionId",
            eventParams = eventParams
        )
        LogEx.logDebug(TAG, "showNotification actionId=$actionId")
        showNotification(applicationContext, intent, remoteViews)
    }

    //创建通知通道
    private fun createNotificationChannel(
        context: Context,
        channelId: String = CHANNEL_ID,
        channelName: String = CHANNEL_NAME,
    ) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(channelId, channelName, importance).apply {
                enableLights(true)
                enableVibration(false)
                vibrationPattern = longArrayOf(0)
                lightColor = Color.RED
            }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    @SuppressLint("MissingPermission")
    //Manifest.permission.POST_NOTIFICATIONS
    fun showNotification(context: Context, intent: Intent, remoteViews: RemoteViews) {

        createNotificationChannel(context)

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_MUTABLE
        } else {
            FLAG_UPDATE_CURRENT
        }

        //requestCode每次需要改变
        val requestCode = Random.nextInt(0, 1000)
        val pendingIntent = PendingIntent.getActivity(
            context, requestCode, intent, flag
        )
        val title = intent.getStringExtra("title")
        val desc = intent.getStringExtra("desc")


        val builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_logo24)
            .setCustomContentView(remoteViews)
            .setCustomBigContentView(remoteViews)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setColor(Color.TRANSPARENT)
            .setContentTitle(title)
            .setContentText(desc)
            .setAutoCancel(true)
            .setOngoing(true)
            .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
            .setVibrate(longArrayOf(0))
            .setContentIntent(pendingIntent)

        val notification: Notification = builder.build()
        val notificationManager = context.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(notificationId, notification)
    }
}

