package ru.omni_devel.cards import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import android.widget.LinearLayout import android.widget.PopupMenu import android.widget.TextView import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.google.android.material.button.MaterialButton import kotlinx.serialization.json.Json import org.w3c.dom.Text class MainActivity : AppCompatActivity() { private lateinit var cardsList: LinearLayout private lateinit var db: DbHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } db = DbHelper(this, null) cardsList = findViewById(R.id.cardsList) val addCardButton: Button = findViewById(R.id.addCardButton) val syncWithWearOSButton: Button = findViewById(R.id.syncWithWearOSButton) addCardButton.setOnClickListener { startActivity(Intent(this, AddCardActivity::class.java)) } syncWithWearOSButton.setOnClickListener { Toast.makeText(this, "Sync in progress...", Toast.LENGTH_SHORT).show() val isSuccess = sendToWatch(this, "/updateCards", Json.encodeToString(db.getCards())) if (isSuccess) { Toast.makeText(this, "Synced!", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Sync failed! Please, check your connection", Toast.LENGTH_LONG).show() } } } override fun onResume() { super.onResume() renderCards() } private fun renderCards() { val cards = db.getCards() cardsList.removeAllViews() if (cards.isEmpty()) { val text = TextView(this) val params = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) text.text = "Add a card to get started" text.layoutParams = params text.textAlignment = View.TEXT_ALIGNMENT_CENTER cardsList.addView(text) } else { for (card in cards) { val button = MaterialButton(this) val params = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) params.setMargins(16, 4, 16, 4) button.text = card.name button.layoutParams = params button.cornerRadius = (12 * resources.displayMetrics.density).toInt() button.setOnClickListener { val intent = Intent(this, ShowCardActivity::class.java) intent.putExtra("cardId", card.id) startActivity(intent) } button.setOnLongClickListener { view -> val popup = PopupMenu(this, view) popup.menu.add("Remove") popup.setOnMenuItemClickListener { menuItem -> when (menuItem.title) { "Remove" -> { db.removeCard(card.id) renderCards() true } else -> false } } popup.show() true } cardsList.addView(button) } } } }