package com.example.salonappnew;

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

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.salonappnew.models.UserType;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.Source;

public class login extends AppCompatActivity {
    private Button logBtn,btn_tmp;
    EditText emailId,password;
    FirebaseAuth mFirebaseAuth;
    private DatabaseReference mFDb;
    private FirebaseDatabase mFirebaseInstant;
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    TextView adminLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        emailId = findViewById(R.id.editTextEmail);
        password = findViewById(R.id.editTextPass);



        mFirebaseAuth = FirebaseAuth.getInstance();

//        DocumentReference docRef = db.collection("users").document("sam");
//        Source source = Source.SERVER;
//
//        docRef.get(source).addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
//            @Override
//            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
//                if (task.isSuccessful()) {
//                    // Document found in the offline cache
//                    DocumentSnapshot document = task.getResult();
//                    Log.d("chata", "Cached document data: " + document.getData());
//                } else {
//                    Log.d("chata", "Cached get failed: ", task.getException());
//                }
//            }
//        });


//        FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();

        if(mFirebaseAuth.getCurrentUser() == null ){
            Toast.makeText(login.this,"current user not found", Toast.LENGTH_LONG).show();

        }else {
            openNewDashboard();
        }

        logBtn = (Button) findViewById(R.id.btn_login);
//        btn_tmp = (Button) findViewById(R.id.btn_tmp);




        logBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fLogin();
            }
        });

//        btn_tmp.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                register();
//            }
//        });



    }

    private void register() {
        if(validatePassAndEmail()){
            String email = emailId.getText().toString();
            String pass = password.getText().toString();
            Log.d("chata","email and password is okay");
            mFirebaseAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d("chata", "createUserWithEmail:success");
                        FirebaseUser user = mFirebaseAuth.getCurrentUser();
//                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w("chata", "createUserWithEmail:failure", task.getException());
                        Toast.makeText(login.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
//                        updateUI(null);
                    }
                }
            });
        }
    }


    public boolean validatePassAndEmail(){
        String email = emailId.getText().toString();
        String pass = password.getText().toString();

        if(email.isEmpty()){
            emailId.setError("Please provide a email id");
            emailId.requestFocus();
            return false;
        }else if(pass.isEmpty()){
            password.setError("Please enter a password");
            password.requestFocus();
            return false;
        }else{
            return true;
        }
    }

//    public void openAdminLogin(){
//        Intent intent = new Intent(this, loginAdmin.class);
//        startActivity(intent);
//    }


    public void fLogin(){

        String email = emailId.getText().toString();
        String pass = password.getText().toString();
//        openNewDashboard();
        if(validatePassAndEmail()){
            mFirebaseAuth.signInWithEmailAndPassword(email, pass)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG).show();
//                            progressBar.setVisibility(View.GONE);

//                            TODO uncomment me after
//                            openNewDashboard();
                            Log.d("chata","fLogin success");

                            checkUserAvailability(email,pass);

                        }
                        else {
                            Toast.makeText(getApplicationContext(), "Login failed! Please try again later", Toast.LENGTH_LONG).show();
//                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
        }


    }


    public void openNewDashboard(){
        Intent intent = new Intent(this, ADHDHome.class);
        startActivity(intent);
    }

    public void checkUserAvailability(String email,String password){
        Log.d("chata","in checkUserAvailability");
        FirebaseUser user = mFirebaseAuth.getCurrentUser();
        Log.d("chata","user id is "+user.getUid());

        //check user availabiliy with firestore
        db.collection("users").whereEqualTo("uid",user.getUid()).get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        Log.d("chata","fire search done");
                        openNewDashboard();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("chata","fire search failed");
                    }
                });

        //if user available redirect to dashboard
//        final ProgressDialog progressDialog = new ProgressDialog(this);
//        progressDialog.setTitle("Checking User Availability...");
//        progressDialog.show();
//        Log.d("Data","Current user"+mFirebaseAuth.getCurrentUser().getEmail());
//        Query data = mFDb.child("userType").orderByChild("email").startAt(mFirebaseAuth.getCurrentUser().getEmail().toString())
//                .endAt(mFirebaseAuth.getCurrentUser().getEmail()+"\uf8ff");

//        data.addListenerForSingleValueEvent(new ValueEventListener() {
//            @Override
//            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//                if(dataSnapshot.exists()){
//                    //bus number exists in Databas
//                    Log.d("Data","Data ->"+dataSnapshot.getValue().toString());
//
//                    UserType userType = dataSnapshot.getValue(UserType.class);
////
//                    Log.d("Data","User type found -> key "+dataSnapshot.getKey());
//                    progressDialog.dismiss();
//                    kill_activity();
//                    searchFireStore(mFirebaseAuth.getCurrentUser().getEmail());
//                    Log.d("Data","Data  found");
//                    SharedPreferences pref =getSharedPreferences("prefs",MODE_PRIVATE);
//                    final SharedPreferences.Editor editor = pref.edit();
//                    editor.putBoolean("loggedin",true);
//                    editor.apply();
//
//                } else {
//                    //bus number doesn't exists.
//                    Toast.makeText(getApplicationContext(), "Login failed! Please try again later", Toast.LENGTH_LONG).show();
////
//                    progressDialog.dismiss();
//                    Log.d("Data","Data not  found");
//
//                }
//            }
//
//            @Override
//            public void onCancelled(@NonNull DatabaseError databaseError) {
//
//            }
//        });
    }

    public void openDashBoard(String type){
//        Intent intent = new Intent(this, Dashboard.class);
//        intent.putExtra("type", type);
//        startActivity(intent);
    }

    public void kill_activity()
    {
        finish();
    }


    private void searchFireStore( String queryText){
        Query data = mFDb.child("userType").orderByChild("email").startAt(queryText)
                .endAt(queryText+"\uf8ff");



        data.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                System.out.println(dataSnapshot.getKey());

                Log.d("Data","Data ->"+dataSnapshot.getKey());
                Log.d("Data","Data ->"+dataSnapshot.getValue().toString());

                UserType userType = dataSnapshot.getValue(UserType.class);

                Log.d("Data","Data ->"+userType.getType());
                openDashBoard(userType.getType());
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}