package com.abbidot.tracker.ui.activity.account

import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityChangeNameBinding
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.UserProfileViewModel

class ChangeNameActivity :
    BaseActivity<ActivityChangeNameBinding>(ActivityChangeNameBinding::inflate) {

    private val mUserViewModel: UserProfileViewModel by viewModels()

    override fun getTopBar() = mViewBinding.ilChangeNameTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_change_name)

        val username = MMKVUtil.getString(MMKVKey.UserName)
        mViewBinding.apply {
            ilChangeNameNameLayout.let {
                it.etInputContent.setText(username)
                it.tvInputNameTitle.text = getString(R.string.register_txt_name)
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext, it.rlEtInputLayout, tvChangeNameNameErrorTip, it.etInputContent
                )
            }

            setOnClickListenerViews(btnChangeNameSave)
        }
    }

    override fun liveDataObserve() {
        mUserViewModel.mUpdateUserInfoLiveData.observe(this@ChangeNameActivity) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val name = mViewBinding.ilChangeNameNameLayout.etInputContent.text.toString()
                    MMKVUtil.putString(MMKVKey.UserName, name)
                    XEventBus.post(EventName.UpdateUserInfo)
                    showToast(R.string.txt_change_successful, true)
                }
            })
        }
    }

    private fun userProfileSave() {
        mViewBinding.apply {
            val name = ilChangeNameNameLayout.etInputContent.text.toString()
            val uploadImageUrl = MMKVUtil.getString(MMKVKey.HeadUrl)
            val countryCode = MMKVUtil.getString(MMKVKey.CountryCode)
            val email = MMKVUtil.getString(MMKVKey.Email)
            if (TextUtils.isEmpty(name)) {
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilChangeNameNameLayout.rlEtInputLayout, tvChangeNameNameErrorTip
                )
                return
            }

            mUserViewModel.updateUserInfo(
                this@ChangeNameActivity, "", uploadImageUrl, countryCode, name
            )
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnChangeNameSave -> userProfileSave()
            }
        }
    }
}