package com.rugvedsarika.cashcounter

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.rugvedsarika.cashcounter.databinding.ActivityHistoryBinding
import com.rugvedsarika.cashcounter.data.AppDatabase
import com.rugvedsarika.cashcounter.data.HistoryDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class HistoryActivity : AppCompatActivity() {

    private lateinit var binding: ActivityHistoryBinding
    private lateinit var historyDao: HistoryDao

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHistoryBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // Setup Toolbar
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        binding.toolbar.setNavigationOnClickListener { finish() }

        // Setup DB
        val db = AppDatabase.getDatabase(this)
        historyDao = db.historyDao()

        // Setup RecyclerView
        val adapter = HistoryAdapter { historyItem ->
            lifecycleScope.launch(Dispatchers.IO) {
                historyDao.delete(historyItem)
            }
        }
        binding.rvHistory.adapter = adapter
        
        // Observe Data
        historyDao.getAllHistory().observe(this) { list ->
            adapter.submitList(list)
            binding.tvEmptyState.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
        }
    }
}
