package com.example.defenseapplication.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.R

data class Device(
    val name: String,
    val icon: String  // 暂时保留，不再实际使用静态图片
)

class AddDeviceAdapter(
    private val devices: List<Device>,
    private val onItemClick: (Device) -> Unit
) : RecyclerView.Adapter<AddDeviceAdapter.ViewHolder>() {

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivIcon: ImageView = itemView.findViewById(R.id.ivDeviceIcon2)
        val tvName: TextView = itemView.findViewById(R.id.tvDeviceName2)

        // 启动帧动画
        fun startAnimation() {
            val drawable = ivIcon.drawable
            if (drawable is android.graphics.drawable.AnimationDrawable && !drawable.isRunning) {
                drawable.start()
            }
        }

        // 停止帧动画
        fun stopAnimation() {
            val drawable = ivIcon.drawable
            if (drawable is android.graphics.drawable.AnimationDrawable && drawable.isRunning) {
                drawable.stop()
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_device2, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val device = devices[position]
        holder.tvName.text = device.name
        holder.ivIcon.setImageResource(R.drawable.img)

        // 点击事件
        holder.itemView.setOnClickListener { onItemClick(device) }
    }

    override fun onViewRecycled(holder: ViewHolder) {
        super.onViewRecycled(holder)
        // 视图被回收时停止动画，节省资源
        holder.stopAnimation()
    }

    override fun getItemCount(): Int = devices.size
}