package com.sshproxy.vpn.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.sshproxy.vpn.data.AppInfo
import com.sshproxy.vpn.databinding.ItemAppExclusionBinding

class AppExclusionAdapter(
    private val onToggle: (AppInfo, Boolean) -> Unit
) : RecyclerView.Adapter<AppExclusionAdapter.ViewHolder>() {

    private var items: List<AppInfo> = emptyList()
    private var excludedPackages: Set<String> = emptySet()
    private var suppressToggleCallback = false

    fun submitList(apps: List<AppInfo>, excluded: Set<String>) {
        items = apps
        excludedPackages = excluded
        notifyDataSetChanged()
    }

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

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

    override fun getItemCount(): Int = items.size

    inner class ViewHolder(
        private val binding: ItemAppExclusionBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(app: AppInfo) {
            binding.appIcon.setImageDrawable(app.icon)
            binding.appName.text = app.label
            binding.appPackage.text = app.packageName

            suppressToggleCallback = true
            binding.excludeSwitch.isChecked = excludedPackages.contains(app.packageName)
            suppressToggleCallback = false

            binding.excludeSwitch.setOnCheckedChangeListener { _, isChecked ->
                if (!suppressToggleCallback) {
                    onToggle(app, isChecked)
                }
            }

            binding.root.setOnClickListener {
                binding.excludeSwitch.isChecked = !binding.excludeSwitch.isChecked
            }
        }
    }
}
