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.ApiErrorParser import com.notifyhub.viewer.data.remote.StatsResponse import com.notifyhub.viewer.databinding.FragmentHomeBinding import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class HomeFragment : Fragment(), HomeActivity.Refreshable { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! private val app get() = (requireActivity().application as NotizViewerApp) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) binding.unreadAlertsList.layoutManager = LinearLayoutManager(requireContext()) binding.unreadAlertsList.adapter = AlertAdapter(emptyList()) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun refresh() = load() override fun onResume() { super.onResume() load() } private fun load() { binding.statusText.visibility = View.GONE lifecycleScope.launch { try { val statsResponse = withContext(Dispatchers.IO) { app.api.stats() } if (!statsResponse.isSuccessful || statsResponse.body() == null) { binding.statusText.text = ApiErrorParser.message(statsResponse) binding.statusText.visibility = View.VISIBLE return@launch } bindStats(statsResponse.body()!!) val alerts = withContext(Dispatchers.IO) { runCatching { app.api.alerts().body() }.getOrNull() } ?: emptyList() val unread = alerts.filter { !it.isRead } binding.unreadAlertsList.adapter = AlertAdapter(unread) binding.unreadAlertsLabel.text = getString(R.string.unread_alerts) } catch (e: Exception) { binding.statusText.text = e.message ?: getString(R.string.no_alerts) binding.statusText.visibility = View.VISIBLE } } } private fun bindStats(stats: StatsResponse) { binding.unreadAlertsValue.text = stats.unreadAlerts.toString() binding.todayMessagesValue.text = stats.todayMessages.toString() } }