package com.hesiii.i_hear.Activities;

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

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.hesiii.i_hear.R;
import com.hesiii.i_hear.databinding.ActivitySignInBinding;

public class SignInActivity extends AppCompatActivity {

    private FirebaseAuth auth;
    private ActivitySignInBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySignInBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        auth = FirebaseAuth.getInstance();

        binding.signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                signInButtonProcess();

            }
        });

    }

    private void signInButtonProcess() {

        String email = binding.emailText.getText().toString().toLowerCase();
        String password = binding.passwordText.getText().toString();

        if (email.isEmpty()) {

            binding.emailText.setError("Enter Valid Email");

        } else if (password.isEmpty()){

            binding.passwordText.setError("Enter Correct Password");

        } else {

            binding.signInButton.setEnabled(false);
            binding.progressBar.setVisibility(View.VISIBLE);
            //pass email & password to server and log user
            userLogin(email, password);

        }

    }

    private void userLogin(String email, String password) {

        auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (task.isSuccessful()) {

                    Toast.makeText(SignInActivity.this, "Successfully Logged In!", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(SignInActivity.this, HomeActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);

                } else {

                    Toast.makeText(SignInActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                }

                binding.signInButton.setEnabled(true);
                binding.progressBar.setVisibility(View.GONE);

            }
        });

    }
}