package com.develop.auth.ui

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import com.develop.auth.R
import com.develop.auth.databinding.FragmentMemberRegisterBinding
import com.develop.food.base.ui.ViewBindingFragment

class MemberRegisterFragment: ViewBindingFragment<FragmentMemberRegisterBinding>() {

    private val viewModel by activityViewModels<MemberViewModel>()

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

    override fun onPostCreateView() {
        binding.tvRegister.setOnClickListener {
            if (!checkInputs()) {
                return@setOnClickListener
            }
            executeRegister(
                binding.etEmailId.text.toString(),
                binding.etPassword.text.toString()
            )
        }
        binding.tvLogin.setOnClickListener {
            parentFragmentManager
                .beginTransaction()
                .replace(R.id.fl_container, MemberLoginFragment())
                .commitAllowingStateLoss()
        }
    }

    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("Please fill in")
            return false
        }
        if (!TextUtils.equals(inputPsd, inputPsdConfirm)) {
            showToast("Password is not the same")
            return false
        }
        return true
    }

    private fun executeRegister(emailId: String, password: String) {
        showDialog()
        viewModel.register(
            emailId, password
        ).observe(this) {
            dismissDialog()
            if (!it) {
                return@observe
            }
            parentFragmentManager
                .beginTransaction()
                .replace(R.id.fl_container, MemberProfileFragment(), "MemberProfileFragment")
                .commitAllowingStateLoss()
        }
    }

}