package com.develop.auth.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import com.develop.auth.R
import com.develop.auth.databinding.FragmentMemberRegisterBinding
import com.develop.auth.viewmodel.FragmentTag
import com.develop.auth.viewmodel.MemberViewModel
import com.develop.base.mvvm.BaseBVMFragment
import com.develop.common.ui.CommonBVMFragment

class MemberRegisterFragment : CommonBVMFragment<FragmentMemberRegisterBinding, MemberViewModel>() {

    override fun createViewBinding(
        inflater: LayoutInflater, container: ViewGroup?
    ): FragmentMemberRegisterBinding {
        return FragmentMemberRegisterBinding.inflate(inflater, container, false)
    }

    override fun onPostCreateView() {
        super.onPostCreateView()
        binding.tvRegister.setOnClickListener {
            if (!checkInputs()) {
                return@setOnClickListener
            }
            executeRegister(
                binding.etEmailId.text.toString(), binding.etPassword.text.toString()
            )
        }
        binding.tvLogin.setOnClickListener {
            viewModel.fragmentChangeLiveData.postValue(FragmentTag.MEMBER_LOGIN)
        }
        viewModel.registerLiveData.observe(viewLifecycleOwner) {
            dismissPlainDialog()
            it.msg?.apply {
                showToast(this)
            }
            if (it.success) {
                viewModel.fragmentChangeLiveData.postValue(FragmentTag.MEMBER_PROFILE)
            }
        }
    }

    private fun checkInputs(): Boolean {
        val inputEmailId = binding.etEmailId.text.toString()
        val inputPsd = binding.etPassword.text.toString()
        val inputPsdConfirm = binding.etPasswordAgain.text.toString()
        if (inputEmailId.isEmpty() || inputPsd.isEmpty()) {
            showToast(getString(com.develop.common.R.string.please_fill_in))
            return false
        }
        if (!TextUtils.equals(inputPsd, inputPsdConfirm)) {
            showToast(getString(com.develop.common.R.string.Password_is_not_the_same))
            return false
        }
        return true
    }

    private fun executeRegister(emailId: String, password: String) {
        showPlainDialog()
        viewModel.register(emailId, password)
    }

    override fun createViewModel(): MemberViewModel {
        return getViewModelOfActivity(MemberViewModel::class.java)
    }

}