package com.base.superfilemanager.notificationclean

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.BarUtils
import com.base.superfilemanager.R
import com.base.superfilemanager.databinding.ActivityLayoutTionCleanBinding
import com.base.superfilemanager.helps.BaseActivity
import com.base.superfilemanager.helps.ConfigHelper
import com.base.superfilemanager.helps.KotlinExt.toFormatTime
import com.base.superfilemanager.helps.ads.AdmobUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlin.random.Random


class NotificationCleanActivity : BaseActivity<ActivityLayoutTionCleanBinding>() {

    private val historyDao by lazy {
        HistoryDatabase.getInstance(this)?.historyDao()
    }
    private val notificationList = mutableListOf<NotificationData>()
    private var isRequest = 0
    override val binding: ActivityLayoutTionCleanBinding by lazy {
        ActivityLayoutTionCleanBinding.inflate(layoutInflater)
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun initView() {

        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        binding.idGant.setOnClickListener {
            val intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
            startActivity(intent)
        }

        binding.idBackNotification.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                AdmobUtils.showInterstitialAd(this@NotificationCleanActivity) {
                    finishToMain()
                }

            }
        })
        binding.idTvCleanAllT.setOnClickListener {
            AdmobUtils.showInterstitialAd(this) {
                MainScope().launch(Dispatchers.IO) {
                    historyDao?.deleteAll()

                }

                mAdapter.notifyDataSetChanged()
                showEmptydata()
            }


        }

        historyDao?.getAll()?.observe(this) {
            if (it.isNotEmpty()) {
                binding.idNoNotification.isVisible = false
                binding.idNotifyClean.isVisible = true
                binding.idViewLine.isVisible = true
                binding.idTvCleanAllT.isVisible = true
                notificationList.clear()
                notificationList.addAll(it)
                binding.idNotifyClean.run {
                    layoutManager = LinearLayoutManager(this@NotificationCleanActivity)
                    adapter = mAdapter
                    mAdapter.notifyDataSetChanged()
                }
            } else {
                showEmptydata()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        val intent = Intent(this, AppNotificationListenerService::class.java)
        startService(intent)
        binding.idNeedNotifcationPremison.isVisible = !ConfigHelper.isOpenNotification
        binding.idImgShezhi.isVisible = false
        if (ConfigHelper.isOpenNotification) {
            isRequest += 1
            playAnimal()
        }
    }

    private fun playAnimal() {
        if (isRequest == 1) {
            binding.idLlAnimation.isVisible = true
            binding.root.postDelayed({
                binding.idLlAnimation.isVisible = false
                AdmobUtils.showInterstitialAd(this)
            }, Random.nextLong(4000, 6000))
        }
    }


    private fun showEmptydata() {
        binding.idNotifyClean.isVisible = false
        binding.idNoNotification.isVisible = true
        binding.idViewLine.isVisible = false
        binding.idTvCleanAllT.isVisible = false
    }

    private val mAdapter by lazy {
        class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val ivImage: ImageView
            val tvTitle: TextView
            val tvContent: TextView
            val tvTime: TextView
            val ivBig: ImageView

            init {
                ivImage = view.findViewById(R.id.id_t_icon)
                tvTitle = view.findViewById(R.id.id_title)
                tvContent = view.findViewById(R.id.id_content)
                tvTime = view.findViewById(R.id.id_time)
                ivBig = view.findViewById(R.id.id_big_img)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@NotificationCleanActivity).inflate(
                    R.layout.item_tion_cleaner, parent, false
                )
                return ViewHolder(view)
            }

            override fun getItemCount() = notificationList.size

            @SuppressLint("SetTextI18n")
            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val c = ConfigHelper.appList?.firstOrNull {
                    it.packageName == notificationList[position].packageName
                }
                holder.ivImage.setImageDrawable(c?.icon)
                if (notificationList[position].notificationText.isNotBlank()) {
                    holder.tvContent.visibility = View.VISIBLE
                    holder.tvContent.text = notificationList[position].notificationText
                } else {
                    holder.tvContent.visibility = View.GONE
                }
                holder.tvTitle.text = notificationList[position].notificationTitle

                holder.tvTime.text = notificationList[position].notificaonTime.toFormatTime()
                holder.itemView.setOnClickListener {
                    MainScope().launch(Dispatchers.IO) {
                        historyDao?.delete(notificationList[position])
                    }
                    notifyDataSetChanged()
                    val intent =
                        packageManager.getLaunchIntentForPackage(notificationList[position].packageName)
                    if (intent != null) {
                        startActivity(intent)
                    }

                }

            }

            override fun onBindViewHolder(
                holder: ViewHolder,
                position: Int,
                payloads: MutableList<Any>
            ) {
                super.onBindViewHolder(holder, position, payloads)
            }
        }
    }


}