package com.kaixed.kchat.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import com.kaixed.kchat.data.objectbox.ObjectBox.get
import com.kaixed.kchat.data.objectbox.entity.Contact
import com.kaixed.kchat.data.objectbox.entity.Contact_
import com.kaixed.kchat.databinding.ActivityContactsDetailBinding
import com.kaixed.kchat.ui.base.BaseActivity
import io.objectbox.Box

class ContactsDetailActivity : BaseActivity<ActivityContactsDetailBinding>() {

    private val contactBox: Box<Contact> by lazy { get().boxFor(Contact::class.java) }

    private var contactId: String? = null

    private var contactNickname: String? = null

    companion object {
        private const val TAG = "ContactsDetailActivity"
    }

    override fun inflateBinding(): ActivityContactsDetailBinding {
        return ActivityContactsDetailBinding.inflate(layoutInflater)
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        contactId = intent.getStringExtra("contactId")

        val contact = getUserInfo(contactId!!)
        if (contact != null) {
            binding.tvContactId.text = "kid: ${contact.username}"
            binding.tvContactSignature.text = contact.signature
//            Log.d(TAG, "onCreate: $contact")
            if (contact.remark?.isNotEmpty() == true) {
                binding.tvRemark.text = contact.remark
                contactNickname = contact.remark
                binding.tvContactName.text = "昵称：${contact.nickname}"
            } else {
                contactNickname = contact.nickname
                binding.tvRemark.text = contact.nickname
                binding.tvContactName.visibility = View.GONE
            }
        }

        setOnListener()
    }

    private fun setOnListener() {
        binding.rlSendMessage.setOnClickListener {
            startActivity(Intent(this, ChatActivity::class.java).apply {
                putExtra("contactId", contactId)
                putExtra("contactNickname", contactId)
            })
        }

        binding.ciSetRemarkAndLabel.setOnClickListener {
            startActivity(Intent(this, SetRemarkAndLabelActivity::class.java).apply {
                putExtra("contactId", contactId)
                putExtra("contactNickname", contactNickname)
            })
        }

        binding.ctb.setOnSettingClickListener {
            startActivity(Intent(this, DataSettingActivity::class.java).apply {
                putExtra("contactId", contactId)
            })
        }
    }

    private fun getUserInfo(contactId: String): Contact? {
        return contactBox
            .query(Contact_.username.equal(contactId))
            .build()
            .findFirst()
    }
}
