package mx.trackermap.TrackerMap.android.session import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.Fragment import com.zhuinden.liveevent.observe import mx.trackermap.TrackerMap.android.databinding.LoginBinding import mx.trackermap.TrackerMap.android.units.UnitsActivity import org.koin.androidx.viewmodel.ext.android.viewModel class LoginFragment : Fragment() { private var _binding: LoginBinding? = null private val binding get() = _binding!! private val loginViewModel: LoginViewModel by viewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = LoginBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupEvents() setupObservers() loginViewModel.restoreSession() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun setupEvents() { binding.usernameEditText.doAfterTextChanged { loginViewModel.email.value = it.toString() } binding.passwordEditText.doAfterTextChanged { loginViewModel.password.value = it.toString() } binding.signinButton.setOnClickListener { loginViewModel.login() } } private fun setupObservers() { loginViewModel.loginState.observe(this) { result -> Log.d("LoginFragment", result.toString()) when (result) { LoginViewModel.LoginState.Loading -> { Toast.makeText(context, "Loading...", Toast.LENGTH_SHORT).show() } LoginViewModel.LoginState.EmailMissing -> { Toast.makeText(context, "Email is missing", Toast.LENGTH_SHORT).show() } LoginViewModel.LoginState.PasswordMissing -> { Toast.makeText(context, "Password is missing", Toast.LENGTH_SHORT).show() } LoginViewModel.LoginState.Failure -> { Toast.makeText(context, "Failed login", Toast.LENGTH_SHORT).show() } LoginViewModel.LoginState.Success -> { val activity = requireActivity() val intent = Intent(activity.applicationContext, UnitsActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) activity.finish() } } } } }