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

import android.content.Intent
import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityEmailAddressBinding
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.UserProfileViewModel

class EmailAddressActivity :
    BaseActivity<ActivityEmailAddressBinding>(ActivityEmailAddressBinding::inflate) {

    private val mRegisterViewModel: UserProfileViewModel by viewModels()

    override fun getTopBar() = mViewBinding.ilEmailAddressTopBar.titleTopBar

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

        mViewBinding.apply {
            setOnClickListenerViews(btnEmailAddressChange, tvEmailAddressShow)
        }
    }

    override fun onResume() {
        super.onResume()
        val email = MMKVUtil.getString(MMKVKey.Email)
        mViewBinding.apply {
            tvEmailAddressShow.text = email
        }
    }

    override fun liveDataObserve() {
        mRegisterViewModel.mGetEmailCodeLiveData.observe(this) {
            mViewBinding.btnEmailAddressChange.isEnabled = true
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    startActivity(Intent(mContext, ChangeEmailActivity::class.java))
                }
            })
        }
    }

    private fun startChange() {
        val email = MMKVUtil.getString(MMKVKey.Email)
        val title = String.format(getString(R.string.txt_change_email_tip), email)
        ViewUtil.instance.showDialog(
            mContext, title, object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    dialog.dismiss()
                    mViewBinding.btnEmailAddressChange.isEnabled = false
                    mRegisterViewModel.getEmailCode(this@EmailAddressActivity, email, 2)
                }
            }, okTextResId = R.string.txt_sure
        )
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnEmailAddressChange -> startChange()
                tvEmailAddressShow -> Util.copyToClipboard(
                    mContext, tvEmailAddressShow.text.toString()
                )
            }
        }
    }
}