package com.base.pdfviewerscannerwhite.ui.cleanjunk

import android.animation.ValueAnimator
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.ParentBean
import com.base.pdfviewerscannerwhite.databinding.ItemJunkParentScanBinding
import com.base.pdfviewerscannerwhite.utils.XmlEx.inflate

class JunkScanAdapter : RecyclerView.Adapter<JunkScanAdapter.ParentViewHolder>() {

    private val beanList = arrayListOf<ParentBean>()

    inner class ParentViewHolder(view: View) : RecyclerView.ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ParentViewHolder {
        return ParentViewHolder(R.layout.item_junk_parent_scan.inflate(parent))
    }

    override fun getItemCount(): Int {
        return beanList.size
    }

    override fun onBindViewHolder(holder: ParentViewHolder, position: Int) {
        val bean = beanList[position]
        val context = holder.itemView.context
        val binding = ItemJunkParentScanBinding.bind(holder.itemView)
        binding.ivIcon.setImageResource(bean.icon)
        binding.tvTitle.text = bean.tittle

        if (bean.playAnimation) {
            val slideInFromRight = AnimationUtils.loadAnimation(holder.itemView.context, R.anim.slide_in_from_right)
            binding.ll.startAnimation(slideInFromRight)
            bean.playAnimation = false
        }

        if (bean.finished) {
            binding.ivRotate.rotation = 0f
            binding.ivRotate.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.xuan))
            bean.rotateValueAnimator?.cancel()
            bean.rotateValueAnimator = null
        } else {
            bean.rotateValueAnimator = ValueAnimator.ofFloat(0f, 360f).apply {
                duration = 1000
                repeatMode = ValueAnimator.RESTART
                repeatCount = ValueAnimator.INFINITE
                interpolator = LinearInterpolator()
                addUpdateListener {
                    binding.ivRotate.rotation = it.animatedValue as Float
                }
                start()
            }
        }

    }

    fun addData(bean: ParentBean, position: Int) {
        beanList.add(bean)
        notifyItemChanged(position)
    }

    fun setFinishScan(position: Int) {
        val bean = beanList[position]
        bean.finished = true
        notifyItemChanged(position)
    }


}