package com.example.defenseapplication.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.databinding.ItemWifiBinding

class WifiListAdapter(
    wifiList: List<String>,
    private val onItemClick: (String) -> Unit
) : RecyclerView.Adapter<WifiListAdapter.ViewHolder>() {

    private val wifiList = mutableListOf<String>().apply { addAll(wifiList) }

    inner class ViewHolder(val binding: ItemWifiBinding) : RecyclerView.ViewHolder(binding.root) {
        init {
            itemView.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    onItemClick(wifiList[position])
                }
            }
        }

        fun bind(wifiName: String) {
            binding.tvWifiName.text = wifiName
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemWifiBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(wifiList[position])
    }

    override fun getItemCount(): Int = wifiList.size
    
    fun updateData(newList: List<String>) {
        wifiList.clear()
        wifiList.addAll(newList)
        notifyDataSetChanged()
    }
    
    fun addData(newList: List<String>) {
        val startPosition = wifiList.size
        val newItems = newList.filter { !wifiList.contains(it) }
        wifiList.addAll(newItems)
        notifyItemRangeInserted(startPosition, newItems.size)
    }
}