package com.ttstd.controller.activity.login;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Toast;

import com.ttstd.controller.R;
import com.ttstd.controller.activity.main.MainActivity;
import com.ttstd.controller.base.mvvm.BaseMvvmActivity;
import com.ttstd.controller.databinding.ActivityLoginBinding;

/**
 * 登录页：用户名 + 密码登录，成功后进入 {@link MainActivity}。
 */
public class LoginActivity extends BaseMvvmActivity<LoginViewModel, ActivityLoginBinding> {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        String lastUsername = viewModel.lastUsername();
        if (!TextUtils.isEmpty(lastUsername)) {
            binding.etUsername.setText(lastUsername);
            binding.etPassword.requestFocus();
        }

        binding.btnLogin.setOnClickListener(v -> doLogin());

        binding.etPassword.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                doLogin();
                return true;
            }
            return false;
        });
    }

    @Override
    protected void initData() {
        viewModel.getLoading().observe(this, loading -> {
            boolean busy = Boolean.TRUE.equals(loading);
            binding.pbLoading.setVisibility(busy ? View.VISIBLE : View.GONE);
            binding.btnLogin.setEnabled(!busy);
            binding.btnLogin.setText(busy ? R.string.login_in_progress : R.string.login_action);
        });

        viewModel.getErrorMessage().observe(this, msg -> {
            if (!TextUtils.isEmpty(msg)) {
                Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            }
        });

        viewModel.getLoginSuccess().observe(this, success -> {
            if (Boolean.TRUE.equals(success)) {
                Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, MainActivity.class));
                finish();
            }
        });
    }

    private void doLogin() {
        String username = binding.etUsername.getText() == null
                ? "" : binding.etUsername.getText().toString();
        String password = binding.etPassword.getText() == null
                ? "" : binding.etPassword.getText().toString();
        viewModel.login(username, password);
    }
}
