package rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto

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.DisciplineedtoBinding
import com.base.datarecovery.databinding.WeaknessedtoBinding
import pokercc.android.expandablerecyclerview.ExpandableAdapter
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.ChildBean
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Deeplyedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatSize
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Dishedto

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

    private val TAG = "JunkExpandAdapter"

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

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

    inner class ParentViewHolder(val binding: DisciplineedtoBinding) : 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 = WeaknessedtoBinding.inflate(inflater, viewGroup, false)
        return ChildViewHolder(binding)
    }

    override fun onCreateGroupViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(viewGroup.context)
        val binding = DisciplineedtoBinding.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.syndromeedto.text = parentBean.title
        parentBean.expanded = expand

        if (parentBean.expanded) {
            viewHolder.binding.cannotedto.setImageResource(R.mipmap.earlyedto)
        } else {
            viewHolder.binding.cannotedto.setImageResource(R.mipmap.wisdomedto)
        }
        if (parentBean.title == "Residual file") {
            viewHolder.binding.budgetedto.text = parentBean.childItem.size.toString() + " items"
        } else {
            viewHolder.binding.budgetedto.text = parentBean.parentSize.toFormatSize(1)
        }

        viewHolder.binding.cannotedto.isVisible = true
        viewHolder.binding.portionedto.isSelected = parentBean.isParentSelected

        bindParentAnimation(parentBean, groupPosition, viewHolder)

        if (parentBean.childItem.isEmpty()) {
            viewHolder.binding.portionedto.setOnClickListener { }
        } else {
            viewHolder.binding.portionedto.setOnClickListener {
                viewHolder.binding.portionedto.isSelected = !viewHolder.binding.portionedto.isSelected
                parentBean.isParentSelected = viewHolder.binding.portionedto.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: Deeplyedto, groupPosition: Int, viewHolder: ParentViewHolder) {
        if (parentBean.isfinish) {
            viewHolder.binding.variableedto.isVisible = false
            viewHolder.binding.portionedto.isVisible = true
            animators[groupPosition]?.cancel()
        } else {
            Dishedto.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.variableedto.rotation = it.animatedValue as Float
                }
                start()
                animators[groupPosition] = this
            }
            viewHolder.binding.variableedto.isVisible = true
            viewHolder.binding.portionedto.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.importanceedto.text = childBean.childname
        viewHolder.binding.clusteredto.isSelected = childBean.isChildSelected
        viewHolder.binding.agreementedto.text = childBean.childSize.toFormatSize()

        when (groupPosition) {
            0 -> {
                holder.binding.lampedto.setImageResource(R.mipmap.layersedto)
                viewHolder.binding.importanceedto.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.lampedto.setImageDrawable(appIcon)
                    } else {
                        holder.binding.lampedto.setImageResource(R.mipmap.updateedto)
                    }
                } catch (e: Exception) {
                    holder.binding.lampedto.setImageResource(R.mipmap.updateedto)
                }
            }

            2 -> {
                holder.binding.lampedto.setImageResource(R.mipmap.spaceedto)
            }

            3 -> {
                holder.binding.lampedto.setImageResource(R.mipmap.bitteredto)
            }
        }


        viewHolder.itemView.setOnClickListener {
            viewHolder.binding.clusteredto.isSelected = !viewHolder.binding.clusteredto.isSelected
            childBean.isChildSelected = viewHolder.binding.clusteredto.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 }
        Dishedto.logDebug(TAG, "addChildData parentBean=$parentBean")
        notifyDataSetChanged()
        chooseSizeChange()
    }

}