package br.com.codetec.saudesabor.ui.login;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;

import java.util.HashMap;

import br.com.codetec.saudesabor.R;
import br.com.codetec.saudesabor.model.ResponseLogin;
import br.com.codetec.saudesabor.service.CarrinhoComprasGlobal;
import br.com.codetec.saudesabor.service.ServiceConector;
import br.com.codetec.saudesabor.utils.SharedPreferenceUtil;
import br.com.codetec.saudesabor.utils.UtilsActivity;
import br.com.codetec.saudesabor.utils.components.alert.CustomAlert;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {

    private static LoginActivity INSTANCE;

    public static ResponseLogin responseLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

//        Picasso.get().setIndicatorsEnabled(true);
        INSTANCE = this;

        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);
        final TextView cadastrarTextView = findViewById(R.id.txtCadastrar);
        final Button loginButton = findViewById(R.id.login);
//        final ProgressBar loadingProgressBar = findViewById(R.id.loading);

        cadastrarTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CadastrarUsuarioActivity.EDIT_MODE = false;
                UtilsActivity.getInstance().startActivity(LoginActivity.this, CadastrarUsuarioActivity.class);
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
//                    loginViewModel.login(usernameEditText.getText().toString(),
//                            passwordEditText.getText().toString());
                }
                return false;
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                realizarLogin(usernameEditText, passwordEditText);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);

        if(SharedPreferenceUtil.getStringPreference(LoginActivity.this, SharedPreferenceUtil.LOGIN_ULTIMO) != null
                && SharedPreferenceUtil.getStringPreference(LoginActivity.this, SharedPreferenceUtil.SENHA_ULTIMO) != null ){
            usernameEditText.setText(SharedPreferenceUtil.getStringPreference(LoginActivity.this, SharedPreferenceUtil.LOGIN_ULTIMO));
            passwordEditText.setText(SharedPreferenceUtil.getStringPreference(LoginActivity.this, SharedPreferenceUtil.SENHA_ULTIMO));
            realizarLogin(usernameEditText, passwordEditText);
        }

    }

    private void realizarLogin(EditText usernameEditText, EditText passwordEditText) {

        Call<ResponseLogin> call = ServiceConector.getService(LoginActivity.this).login(usernameEditText.getText().toString(), passwordEditText.getText().toString());
        call.enqueue(new Callback<ResponseLogin>() {
            @Override
            public void onResponse(Call<ResponseLogin> call, Response<ResponseLogin> response) {
                if(response.body() != null) {
                    if (!response.body().getErro()) {
                        responseLogin = response.body();
                        CarrinhoComprasGlobal.mapCarrinho = new HashMap<>();

                        SharedPreferenceUtil.setStringPreference(LoginActivity.this, SharedPreferenceUtil.LOGIN_ULTIMO,usernameEditText.getText().toString());
                        SharedPreferenceUtil.setStringPreference(LoginActivity.this, SharedPreferenceUtil.SENHA_ULTIMO,passwordEditText.getText().toString());

                        UtilsActivity.getInstance().startActivity(LoginActivity.this, DashboardActivity.class);
                    } else {
                        CustomAlert.getInstance().show(LoginActivity.this, response.body().getTitulo(), response.body().getMensagem());
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseLogin> call, Throwable t) {
                t.printStackTrace();
                CustomAlert.getInstance().show(LoginActivity.this, getString(R.string.falha_comunicacao));
            }
        });
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

    public static LoginActivity getInstance(){
        return INSTANCE;
    }

}
