package com.kaviz.heal.Activities;

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

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.RadioButton;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.kaviz.heal.Activities.Authentication.RegisterActivity;
import com.kaviz.heal.Model.User;
import com.kaviz.heal.R;
import com.kaviz.heal.databinding.ActivityUserDetailsBinding;

import java.util.Objects;

public class UserDetailsActivity extends AppCompatActivity {

    private static final int IMAGE_REQUEST_CODE = 100;
    private ActivityUserDetailsBinding binding;

    //firebase objects
    private FirebaseAuth auth;
    private FirebaseDatabase database;

    private Uri imageURI;
    private String imageURL = "default";
    private String gender = "none";

    private ProgressDialog showDialog;

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

        //initialize objects
        auth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();

        //for enable show dialog object
        showDialog();

        //for add click event change profile (open gallery)
        binding.userProfilePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                openImageChooser();

            }
        });

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

                registerButtonProcess();

            }
        });

    }

    //handle register button
    private void registerButtonProcess() {

        String name = binding.nameText.getText().toString();
        String height = binding.heightText.getText().toString();
        String weight = binding.weightText.getText().toString();
        String address = binding.addressText.getText().toString();

        int selectedRadioButtonID = binding.genderGroup.getCheckedRadioButtonId();
        RadioButton selectedRadioButton = findViewById(selectedRadioButtonID);

        if (selectedRadioButton != null) {

            gender = selectedRadioButton.getText().toString();

        }

        if (name.isEmpty()) {

            binding.nameText.setError("Enter Name");

        } else if (height.isEmpty()){

            binding.heightText.setError("Enter Height");

        } else if (weight.isEmpty()) {

            binding.weightText.setError("Enter Weight");

        } else if (address.isEmpty()) {

            binding.addressText.setError("Enter Address");

        } else if (gender.equals("none")) {

            Toast.makeText(this, "Please Select Your Gender", Toast.LENGTH_SHORT).show();

        } else {

            showDialog.show();
            binding.submitButton.setEnabled(false);
            User user = new User(name, Double.parseDouble(height), Double.parseDouble(weight), address, gender, imageURL);
            registerUser(user);

        }

    }

    //for register user
    private void registerUser(User user) {

        database.getReference().child("UserDetails").child(auth.getCurrentUser().getUid())
                .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        if (task.isSuccessful()) {

                            showToast("Data Successfully Submitted!");
                            startActivity(new Intent(UserDetailsActivity.this, HomeActivity.class));
                            finishAffinity();

                        } else {

                            showToast("Error - "+task.getException().getMessage());

                        }

                        showDialog.dismiss();
                        binding.submitButton.setEnabled(false);

                    }
                });

    }

    //method for open image chooser (gallery)
    private void openImageChooser() {

        Intent intent = new Intent();
        intent.setType("image/");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);

    }

    private void showDialog() {

        showDialog = new ProgressDialog(this);
        showDialog.setMessage("Please Wait");
        showDialog.setCancelable(false);

    }

    //for get image url
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {

            if (data != null) {

                if (data.getData() != null) {

                    imageURI = data.getData();
                    uploadImage();

                }

            }

        }

    }

    //for upload image to firebase
    private void uploadImage() {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading Image");
        progressDialog.setMessage("Please Wait...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        StorageReference fileReference = FirebaseStorage.getInstance().getReference().child("Uploads")
                .child(System.currentTimeMillis()+"."+getFileExtension(imageURI));
        fileReference.putFile(imageURI).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                if (task.isSuccessful()) {

                    fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {

                            try {

                                imageURL = uri.toString();
                                Glide.with(UserDetailsActivity.this).load(imageURL).placeholder(R.drawable.user_placeholder).into(binding.userProfilePicture);
                                progressDialog.dismiss();
                                Toast.makeText(UserDetailsActivity.this, "Successfully Profile Picture Uploaded!", Toast.LENGTH_SHORT).show();

                            } catch (Exception e) {

                                Toast.makeText(UserDetailsActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();

                            }

                        }
                    });

                } else {

                    Toast.makeText(UserDetailsActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();

                }

            }
        });

    }

    //for get image extension
    private String getFileExtension(Uri imageURI) {

        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(imageURI));

    }

    private void showToast(String message) {

        Toast.makeText(this, message, Toast.LENGTH_LONG).show();

    }

}