package com.notifyhub.viewer.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.notifyhub.viewer.NotizViewerApp import com.notifyhub.viewer.R import com.notifyhub.viewer.data.remote.AlertItem import com.notifyhub.viewer.databinding.FragmentAlertsBinding import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class AlertsFragment : Fragment(), HomeActivity.Refreshable { private var _binding: FragmentAlertsBinding? = null private val binding get() = _binding!! private val app get() = (requireActivity().application as NotizViewerApp) private val items = mutableListOf() private lateinit var adapter: AlertAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentAlertsBinding.inflate(inflater, container, false) adapter = AlertAdapter(items) { item -> markRead(item) } binding.alertsList.layoutManager = LinearLayoutManager(requireContext()) binding.alertsList.adapter = adapter binding.markAllReadButton.setOnClickListener { lifecycleScope.launch { withContext(Dispatchers.IO) { runCatching { app.api.markAllAlertsRead() } } refresh() } } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun refresh() = load() override fun onResume() { super.onResume() load() } private fun load() { lifecycleScope.launch { try { val response = withContext(Dispatchers.IO) { app.api.alerts() } items.clear() response.body()?.let { items.addAll(it) } adapter.notifyDataSetChanged() binding.emptyText.visibility = if (items.isEmpty()) View.VISIBLE else View.GONE binding.emptyText.text = getString(R.string.no_alerts) } catch (e: Exception) { binding.emptyText.text = e.message ?: getString(R.string.no_alerts) binding.emptyText.visibility = View.VISIBLE } } } private fun markRead(item: AlertItem) { if (item.isRead) return lifecycleScope.launch { withContext(Dispatchers.IO) { runCatching { app.api.markAlertRead(item.id) } } refresh() } } }