package rallyedto.dumpedto.editionedto

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.core.view.isVisible
import com.base.datarecovery.R
import com.base.datarecovery.databinding.LifestyleedtoBinding
import com.base.datarecovery.databinding.TileedtoBinding
import pokercc.android.expandablerecyclerview.ExpandableAdapter
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatSize
import rallyedto.policeedto.huntedto.ChildBean
import rallyedto.policeedto.huntedto.Registeredto
import rallyedto.talledto.blewedto.Musicaledto

class Eagleedto(private val chooseAction: (size: Long) -> Unit) : ExpandableAdapter<ExpandableAdapter.ViewHolder>() {

    private val TAG = "JunkExpandAdapter"

    private val parentBeanList by lazy {
        mutableListOf(
            Registeredto(
                title = "Residual file",
                isParentSelected = true,
                expanded = false
            ),
            Registeredto(
                title = "Useless installation package",
                isParentSelected = true,
                expanded = false
            ),
            Registeredto(
                title = "Temp File",
                isParentSelected = true,
                expanded = false
            ),
            Registeredto(
                title = "Log File",
                isParentSelected = true,
                expanded = false
            )
        )
    }
    var animators = mutableMapOf<Int, ValueAnimator>()

    inner class ChildViewHolder(val binding: LifestyleedtoBinding) : ViewHolder(binding.root)

    inner class ParentViewHolder(val binding: TileedtoBinding) : ViewHolder(binding.root)

    override fun getChildCount(groupPosition: Int): Int {
        return parentBeanList[groupPosition].childItem.size
    }

    override fun getGroupCount(): Int {
        return parentBeanList.size
    }

    override fun onCreateChildViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(viewGroup.context)
        val binding = LifestyleedtoBinding.inflate(inflater, viewGroup, false)
        return ChildViewHolder(binding)
    }

    override fun onCreateGroupViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(viewGroup.context)
        val binding = TileedtoBinding.inflate(inflater, viewGroup, false)
        return ParentViewHolder(binding)
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun onBindGroupViewHolder(holder: ViewHolder, groupPosition: Int, expand: Boolean, payloads: List<Any>) {
        val viewHolder = holder as? ParentViewHolder ?: return
        val parentBean = parentBeanList[groupPosition]

        viewHolder.binding.normaledto.text = parentBean.title
        parentBean.expanded = expand

        if (parentBean.expanded) {
            viewHolder.binding.betrayedto.setImageResource(R.mipmap.climbedto)
        } else {
            viewHolder.binding.betrayedto.setImageResource(R.mipmap.castedto)
        }
        if (parentBean.title == "Residual file") {
            viewHolder.binding.whiteedto.text = parentBean.childItem.size.toString() + " items"
        } else {
            viewHolder.binding.whiteedto.text = parentBean.parentSize.toFormatSize(1)
        }

        viewHolder.binding.betrayedto.isVisible = true
        viewHolder.binding.intensifyedto.isSelected = parentBean.isParentSelected

        bindParentAnimation(parentBean, groupPosition, viewHolder)

        if (parentBean.childItem.isEmpty()) {
            viewHolder.binding.intensifyedto.setOnClickListener { }
        } else {
            viewHolder.binding.intensifyedto.setOnClickListener {
                viewHolder.binding.intensifyedto.isSelected = !viewHolder.binding.intensifyedto.isSelected
                parentBean.isParentSelected = viewHolder.binding.intensifyedto.isSelected

                parentBean.childItem.forEach {
                    it.isChildSelected = parentBean.isParentSelected
                }
                notifyDataSetChanged()

                chooseSizeChange()
            }
        }

    }

    override fun onGroupViewHolderExpandChange(holder: ViewHolder, groupPosition: Int, animDuration: Long, expand: Boolean) {}

    private fun chooseSizeChange() {
        val selectSize = parentBeanList.sumOf { it.childItem.filter { it.isChildSelected }.sumOf { it.childSize } }
        chooseAction.invoke(selectSize)
    }

    fun getChoosePath(): List<ChildBean> {
        return parentBeanList.flatMap { it.childItem }.filter { it.isChildSelected }
    }

    fun getAllChildItemCount(): Int {
        return parentBeanList.flatMap { it.childItem }.size
    }

    private fun bindParentAnimation(parentBean: Registeredto, groupPosition: Int, viewHolder: ParentViewHolder) {
        if (parentBean.isfinish) {
            viewHolder.binding.coinedto.isVisible = false
            viewHolder.binding.intensifyedto.isVisible = true
            animators[groupPosition]?.cancel()
        } else {
            Musicaledto.logDebug(TAG, "play parent ValueAnimator")
            animators[groupPosition] ?: ValueAnimator.ofFloat(0f, 360f).apply {
                duration = 1000
                repeatMode = ValueAnimator.RESTART
                repeatCount = ValueAnimator.INFINITE
                interpolator = LinearInterpolator()
                addUpdateListener {
                    viewHolder.binding.coinedto.rotation = it.animatedValue as Float
                }
                start()
                animators[groupPosition] = this
            }
            viewHolder.binding.coinedto.isVisible = true
            viewHolder.binding.intensifyedto.isVisible = false
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun onBindChildViewHolder(holder: ViewHolder, groupPosition: Int, childPosition: Int, payloads: List<Any>) {
        val viewHolder = holder as? ChildViewHolder ?: return
        val childBean = parentBeanList[groupPosition].childItem[childPosition]
        val parentBean = parentBeanList[groupPosition]
        val context = holder.itemView.context

        viewHolder.binding.embarkedto.text = childBean.childname
        viewHolder.binding.childrenedto.isSelected = childBean.isChildSelected
        viewHolder.binding.seatedto.text = childBean.childSize.toFormatSize()

        when (groupPosition) {
            0 -> {
                holder.binding.mustedto.setImageResource(R.mipmap.essayedto)
                viewHolder.binding.embarkedto.text = childBean.chilepath
            }

            1 -> {
                try {
                    val apkFilePath = childBean.chilepath // 替换成您的APK文件路径
                    val packageInfo =
                        context.packageManager.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES)
                    if (packageInfo != null) {
                        val applicationInfo = packageInfo.applicationInfo
                        val appIcon: Drawable = context.packageManager.getApplicationIcon(applicationInfo)
                        viewHolder.binding.mustedto.setImageDrawable(appIcon)
                    } else {
                        holder.binding.mustedto.setImageResource(R.mipmap.otheredto)
                    }
                } catch (e: Exception) {
                    holder.binding.mustedto.setImageResource(R.mipmap.otheredto)
                }
            }

            2 -> {
                holder.binding.mustedto.setImageResource(R.mipmap.backgroundedto)
            }

            3 -> {
                holder.binding.mustedto.setImageResource(R.mipmap.unicornedto)
            }
        }


        viewHolder.itemView.setOnClickListener {
            viewHolder.binding.childrenedto.isSelected = !viewHolder.binding.childrenedto.isSelected
            childBean.isChildSelected = viewHolder.binding.childrenedto.isSelected
            parentBean.isParentSelected = parentBean.childItem.all { it.isChildSelected }
            notifyDataSetChanged()
            chooseSizeChange()
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    fun addChildData(position: Int, childBeanList: List<ChildBean>) {
        val parentBean = parentBeanList[position]
        parentBean.isfinish = true
        parentBean.isParentSelected = true
        parentBean.childItem.addAll(childBeanList)
        parentBean.parentSize = childBeanList.sumOf { it.childSize }
        Musicaledto.logDebug(TAG, "addChildData parentBean=$parentBean")
        notifyDataSetChanged()
        chooseSizeChange()
    }

}