package com.test.basd.smartjunkcleaner.display

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_MUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.RemoteViews
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.test.basd.smartjunkcleaner.R
import com.test.basd.smartjunkcleaner.activity.splash.NewSplashActivity
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_APP_MANAGER
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_BATTERY_PUSH
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_CHARGE
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_CLEAN_NOTIFICATION
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_INSTALL_PACKAGE_PUSH
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_JUNK_CLEAN_PUSH
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_LARGE_FILE_PUSH
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_LOW_BATTERY_PUSH
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_NETWORK_TRAFFIC
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_PHOTO_COMPRESS
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_RECENT_USE_APP
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_SIMILAR_IMAGE
import com.test.basd.smartjunkcleaner.bean.ConfigBean.Companion.ID_UNINSTALL_PACKAGE_PUSH
import com.test.basd.smartjunkcleaner.helps.BaseApplication
import com.test.basd.smartjunkcleaner.helps.ComUtils
import com.test.basd.smartjunkcleaner.helps.EventHelper

import kotlin.random.Random


/**
 * 推送的帮助类
 */
object NotificationHelper {


    private val TAG = "NotificationHelper"
    val notificationId = 19086


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

    /**
     * 过滤可推送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.getSpConfigBean().push_circle_order
        Log.d(TAG, "push_circle_order=$pushCircleOrder")
        val tempList = arrayListOf<Int>()

        val json = SPUtils.getInstance().getString("push_circle_order", "")
        if ((json == "") or (json == "null")) {//初始化
            val filterList = filterAction(pushCircleOrder)
            val initJson = Gson().toJson(filterList)
            SPUtils.getInstance().getString("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)
                SPUtils.getInstance().put("push_circle_order", saveJson)
                tempList.addAll(filterList)
            }
        }

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

        val usedJson = Gson().toJson(tempList)
        SPUtils.getInstance().put("push_circle_order", usedJson)
        return i
    }

    /**
     * 发送通知对于
     * @param extra 额外参数
     */
    @SuppressLint("RemoteViewLayout")
    fun Context.postActionNotification(actionId: Int, extra: Int? = null, pushStayTime: Long? = null) {
        val remoteViews = RemoteViews(packageName, R.layout.notification_common_notify)
        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.cleanjunk_home)
                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.mipmap.virus)
//                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.mipmap.battery)
//                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_LARGE_FILE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.large_home)
                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.mipmap.photo_home)
                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.mipmap.appmanager)
                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.mipmap.network_tools)
                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.mipmap.notification_tools)
                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.mipmap.recentapp_tools)
                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.mipmap.similar_home)
                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.mipmap.speaker_home)
//                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.mipmap.install)
                remoteViews.setTextViewText(R.id.tv_desc, "Installation successful. Delete useless APKs")
                remoteViews.setTextViewText(R.id.tv_btn, "Scan")
            }

            ID_UNINSTALL_PACKAGE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.uninstall)
                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.mipmap.start)
                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.mipmap.battery_lower)
                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.mipmap.memory)
//                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事件,经过测试Intent.action这里无法传递参数
        val cancelIntent = Intent(this, CloseNotificationReceiver::class.java)
        val cancelRequestCode = Random.nextInt(0, 1000)
        val cancelPendingIntent = PendingIntent.getBroadcast(BaseApplication.context, cancelRequestCode, cancelIntent, flag)
        remoteViews.setOnClickPendingIntent(R.id.fl_cancel, cancelPendingIntent)

        val intent = Intent(applicationContext, NewSplashActivity::class.java)
        val title: String = ""
        val desc: String = ""
        intent.putExtra("title", title)
        intent.putExtra("desc", desc)
        val customKey = "type"
        intent.putExtra(customKey, actionId)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        val bundle = Bundle()
        bundle.putInt(customKey, actionId)
        intent.putExtras(bundle)
        val uri =
            Uri.parse("cleanapp://com.test.basd.cleanmaster/com.test.basd.cleanmaster.activity.splash.NewSplashActivity?type=$actionId")
        intent.data = uri
//        intent.data = Uri.parse("myapp://splash?type=$actionId")
        //按钮事件
        val btnRequestCode = Random.nextInt(0, 1000)
        val btnPendingIntent = PendingIntent.getActivity(BaseApplication.context, btnRequestCode, intent, flag)
        remoteViews.setOnClickPendingIntent(R.id.fl_btn, btnPendingIntent)

        //每种类型保存值
        SPUtils.getInstance().put(actionId.toString(), System.currentTimeMillis())
        //大间隔所需值
        SPUtils.getInstance().put("all_last_push_time", System.currentTimeMillis())
        EventHelper.event(
            "pushCircleOrder_showNotification",
            "actionId=$actionId"
        )
        val requestCode = Random.nextInt(0, 1000)

        val pendingIntent = PendingIntent.getActivity(applicationContext, requestCode, intent, FLAG_UPDATE_CURRENT or FLAG_MUTABLE)
        NotificationUtils.showNotification(
            applicationContext,
            notificationId,
            remoteViews,
            R.id.fl_cancel,
            pendingIntent,
            pushStayTime ?: 0
        )

    }
}
