package com.dmc.callcrm.ui import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.dmc.callcrm.R import com.dmc.callcrm.data.CallStats import com.google.android.material.tabs.TabLayout class ContactsFragment : Fragment() { private lateinit var adapter: ContactAdapter private var all: List = emptyList() private var query = "" override fun onCreateView(i: LayoutInflater, c: ViewGroup?, s: Bundle?): View = i.inflate(R.layout.fragment_list, c, false) override fun onViewCreated(v: View, s: Bundle?) { v.findViewById(R.id.title).text = "Contacts" v.findViewById(R.id.tabs).visibility = View.GONE adapter = ContactAdapter(emptyList()) { num -> dial(num) } v.findViewById(R.id.list).apply { layoutManager = LinearLayoutManager(context); adapter = this@ContactsFragment.adapter } v.findViewById(R.id.search).addTextChangedListener(object : TextWatcher { override fun afterTextChanged(e: Editable?) { query = e?.toString()?.trim().orEmpty(); render() } override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} }) all = CallStats(requireContext()).contacts(200) render() } private fun render() { val list = if (query.isEmpty()) all else all.filter { (it.name ?: "").contains(query, true) || it.number.contains(query) } adapter.submit(list) } private fun dial(number: String) { try { startActivity(android.content.Intent(android.content.Intent.ACTION_DIAL, android.net.Uri.parse("tel:$number"))) } catch (_: Exception) {} } }