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

import android.content.Intent
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.constant.GetResultCallback
import com.abbidot.tracker.ui.fragment.account.EmailValidFragment
import com.abbidot.tracker.ui.fragment.account.ForgotPasswordV2OneFragment
import com.abbidot.tracker.vm.UserProfileViewModel

class ChangeEmailActivity : AddEmailValidActivity() {

    private val mUserViewModel: UserProfileViewModel by viewModels()

    override fun initData() {
        //验证老的邮箱验证码
        val oldEmailValidFragment = EmailValidFragment.newInstance(mContext, 2) {
            switchFragment(1)
        }.apply {
            setEmail(MMKVUtil.getString(MMKVKey.Email))
        }
        mEmailValidFragment =
            EmailValidFragment.newInstance(mContext, 3, getString(R.string.txt_change_now)) {
                updateEmail()
            }
        mFragmentList = mutableListOf(
            oldEmailValidFragment, ForgotPasswordV2OneFragment.newInstance(
                mContext, getString(R.string.txt_enter_new_email), 3, 1
            ), mEmailValidFragment
        )
        super.initData()
    }

    override fun liveDataObserve() {
        mUserViewModel.mUpdateUserInfoLiveData.observe(this@ChangeEmailActivity) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    MMKVUtil.putString(MMKVKey.Email, mUserEmail)
                    XEventBus.post(EventName.UpdateUserInfo)
                    startActivityFinish(Intent(mContext, ChangeEmailSuccessActivity::class.java))
                }
            })
        }
    }

    private fun updateEmail() {
        val name = MMKVUtil.getString(MMKVKey.UserName)
        val countryCode = MMKVUtil.getString(MMKVKey.CountryCode)
        val email = mUserEmail
        val imageUrl = MMKVUtil.getString(MMKVKey.HeadUrl)
        mUserViewModel.updateUserInfo(
            this@ChangeEmailActivity, email, imageUrl, countryCode, name
        )
    }
}