package com.ccwangluo.im.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.ccwangluo.im.MainActivity2;
import com.ccwangluo.im.data.LoginViewModel;
import com.ccwangluo.im.databinding.ActivityLoginBinding;
import com.ccwangluo.im.util.ToastUtil;


public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;
    private ActivityLoginBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loginViewModel = new ViewModelProvider(this)
                .get(LoginViewModel.class);

        final EditText usernameEditText = binding.username;
        final EditText UserIdEditText = binding.password;
        final Button loginButton = binding.login;

        loginViewModel.loginState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
//                    Intent intent = new Intent(LoginActivity.this, MainActivity2.class);
//                    startActivity(intent);
                    finish();

                }
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                if (TextUtils.isEmpty(username)) {
                    ToastUtil.show(LoginActivity.this, "username is empty");
                    return;
                }
                String id = UserIdEditText.getText().toString();
                if (TextUtils.isEmpty(id)) {
                    ToastUtil.show(LoginActivity.this, "userid is empty");
                    return;
                }
                String appkey = binding.appkey.getText().toString();
                String appSecret = binding.appSecret.getText().toString();
                String ip = binding.ip.getText().toString();
                String server = binding.server.getText().toString();
                int port = Integer.parseInt(binding.port.getText().toString());
                loginViewModel.login(getApplicationContext(),appkey,appSecret,username, id,server,ip,port);
            }
        });
    }
}