package com.project.ilsaenterprise.account;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
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.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.project.ilsaenterprise.Home;
import com.project.ilsaenterprise.R;
import com.project.ilsaenterprise.SharedPref;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.thekhaeng.pushdownanim.PushDownAnim;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

public class CreateUser extends AppCompatActivity {
    private static final int PICK_IMAGE_INTENT = 1;
    private TextView tvName, tvNoPeg, tvJabatan, tvLokasi, tvEmail, tvHp;
    private RelativeLayout updateAccountBtn, editAccountBtn;
    private CircleImageView userProfileImage;
    private final DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("users")
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());

    SharedPref sharedPreference;
    private DatabaseReference userRef;
    private DatabaseReference userPhotoRef;
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;
    private static final int GalleryPick = 1;
    private StorageReference UserProfileImgRef;
    private ProgressBar progressUpload;
    private TextView progressTxt;
    private String android_id;
    HashMap<String, String> profileMap;
    Uri media_camera;
    private com.getbase.floatingactionbutton.FloatingActionButton btnAddCam, btnAddGallery;
    private static final String WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private static final String CAMERA_USAGE = Manifest.permission.CAMERA;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 101;
    private static final int STORAGE_PERMISSION_REQUEST_CODE = 102;
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 103;
    private Boolean mWriteExternalStorage = false;
    private Boolean mCameraPermission = false;
    private static final int IMAGE_CAPTURE_CODE = 101;
    private GoogleSignInAccount googleLogin;
    private String valHp;
    TextView tvGender, tvClass, tvCompany, tvDOB, tvAddress, tvNIP, tvDivision;
    ImageView btnChangeName, btnChangeDOB, btnChangeGender, btnChangeAddress, btnChangeClass, btnChangeCompany, btnChangePhone, btnChangeDivision, btnChangeNIP;
    RelativeLayout btnSaveEnable, btnSaveDisable;
    private DatePickerDialog datePickerDialog;
    private SimpleDateFormat dateFormatter;
    private int selectedCompany;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getSupportActionBar() != null)
            getSupportActionBar().hide();
        setContentView(R.layout.activity_create_user);

        sharedPreference = new SharedPref(this);
        mAuth = FirebaseAuth.getInstance();
        userFirebase = mAuth.getCurrentUser();
        userRef = FirebaseDatabase.getInstance().getReference().child("users");
        UserProfileImgRef = FirebaseStorage.getInstance().getReference().child("profileImage");
        userPhotoRef = FirebaseDatabase.getInstance().getReference().child("usersPhoto");
        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        userRef.child(userFirebase.getUid()).child("uid").setValue(userFirebase.getUid());
        dateFormatter = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
        selectedCompany = 1;

        InitializeFields();

        btnChangeName = findViewById(R.id.ivChangeName);
        btnChangeDOB = findViewById(R.id.ivChangeDOB);
        btnChangeGender = findViewById(R.id.ivChangeGender);
        btnChangeDivision = findViewById(R.id.ivChangeDivision);
        btnChangeClass = findViewById(R.id.ivChangeClass);
        btnChangeCompany = findViewById(R.id.ivChangeCompany);
        btnChangePhone = findViewById(R.id.ivChangeHP);
        btnChangeAddress = findViewById(R.id.ivChangeAddress);
        btnChangeNIP = findViewById(R.id.ivChangeNIP);

        final Resources res = getResources();
        String[] gender = res.getStringArray(R.array.gender);
        String[] userClass = res.getStringArray(R.array.userClass);
        String[] company = res.getStringArray(R.array.company);
        String[] division = res.getStringArray(R.array.userDivision);

        btnChangeName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialogInsert(R.layout.layout_popup_insert, "Nama Lengkap");
            }
        });

        btnChangePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialogInsert(R.layout.layout_popup_insert, "Handphone");
            }
        });

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

        btnChangeAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialogInsert(R.layout.layout_popup_insert, "Alamat");
            }
        });

        btnChangeGender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialog(R.layout.layout_popup_selected, "Gender", gender);
            }
        });

        btnChangeClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialog(R.layout.layout_popup_selected, "Jabatan", userClass);
            }
        });

        btnChangeCompany.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialog(R.layout.layout_popup_selected, "Perusahaan", company);
            }
        });

        btnChangeNIP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialogInsert(R.layout.layout_popup_insert, "NIP");
            }
        });

        btnChangeDivision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialog(R.layout.layout_popup_selected, "Divisi", division);
            }
        });

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


        retrieveInfo();
    }

    private void saveData(){
        try{
            userRef.child(userFirebase.getUid()).child("uid").setValue(userFirebase.getUid());
            userRef.child(userFirebase.getUid()).child("namaLengkap").setValue(tvName.getText().toString());
            userRef.child(userFirebase.getUid()).child("noPeg").setValue(tvNoPeg.getText().toString());
            userRef.child(userFirebase.getUid()).child("jabatan").setValue(tvClass.getText().toString());
            userRef.child(userFirebase.getUid()).child("noHp").setValue(tvHp.getText().toString());
            userRef.child(userFirebase.getUid()).child("email").setValue(tvEmail.getText().toString());
            userRef.child(userFirebase.getUid()).child("perusahaan").setValue(String.valueOf(selectedCompany));
            userRef.child(userFirebase.getUid()).child("penempatan").setValue(tvAddress.getText().toString());
            userRef.child(userFirebase.getUid()).child("DOB").setValue(tvDOB.getText().toString());
            userRef.child(userFirebase.getUid()).child("gender").setValue(tvGender.getText().toString());
            userRef.child(userFirebase.getUid()).child("alamat").setValue(tvAddress.getText().toString());
            userRef.child(userFirebase.getUid()).child("divisi").setValue(tvDivision.getText().toString());
            userRef.child(userFirebase.getUid()).child("nip").setValue(tvNIP.getText().toString());
            userRef.child(userFirebase.getUid()).child("deviceId").setValue(getDeviceName());
            Toast.makeText(getBaseContext(), "Profil telah diperbarui", Toast.LENGTH_SHORT).show();
            toHomeActivity();
        }catch (Exception ex){
            Toast.makeText(getBaseContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void toHomeActivity(){
        Intent homeIntent = new Intent(CreateUser.this, Home.class);
        homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(homeIntent);
        finish();
    }

    private void showAlertDialog(int layout, String selection, String[] SelectionArr){
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(CreateUser.this);
        View layoutView = getLayoutInflater().inflate(layout, null);
        //Button dialogButton = layoutView.findViewById(R.id.btnDialog);

        dialogBuilder.setView(layoutView);
        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.show();

        List<String> listSelection = new ArrayList<>(Arrays.asList(SelectionArr));

        ListView lvItem = layoutView.findViewById(R.id.lvDistrict);
        TextView tvSelection = layoutView.findViewById(R.id.tvSelection);

        tvSelection.setText(selection);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_item_simple, R.id.tvItem, listSelection);
        lvItem.setAdapter(arrayAdapter);

        final String[] selected = {""};
        lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                selected[0] = adapterView.getItemAtPosition(pos).toString();

                if(selection.equals("Gender")){
                    tvGender.setText(selected[0]);
                    checkForm();
                }
                else if(selection.equals("Jabatan")){
                    tvClass.setText(selected[0]);
                    checkForm();
                }
                else if(selection.equals("Perusahaan")){
                    tvCompany.setText(selected[0]);
                    selectedCompany = pos + 1;
                    checkForm();
                }
                else if(selection.equals("Divisi")){
                    tvDivision.setText(selected[0]);
                    checkForm();
                }

                alertDialog.cancel();
            }
        });

    }

    private void showAlertDialogInsert(int layout, String selection){
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(CreateUser.this);
        View layoutView = getLayoutInflater().inflate(layout, null);

        dialogBuilder.setView(layoutView);
        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.show();

        TextView tvSelection = layoutView.findViewById(R.id.tvSelection);
        EditText edtItem = layoutView.findViewById(R.id.edtItem);
        tvSelection.setText(selection);

        if(selection.equals("Handphone"))
            edtItem.setInputType(InputType.TYPE_CLASS_PHONE);
        else if(selection.equals("NIP"))
            edtItem.setInputType(InputType.TYPE_CLASS_NUMBER);

        layoutView.findViewById(R.id.btnFinish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(selection.equals("Nama Lengkap")){
                    tvName.setText(edtItem.getText());
                    checkForm();
                }
                else if(selection.equals("Handphone")){
                    tvHp.setText(edtItem.getText());
                    checkForm();
                }
                else if(selection.equals("Alamat")){
                    tvAddress.setText(edtItem.getText());
                    checkForm();
                }
                else if(selection.equals("NIP")){
                    tvNIP.setText(edtItem.getText());
                    checkForm();
                }

                alertDialog.cancel();
            }
        });
    }

    private void InitializeFields() {
        tvGender = findViewById(R.id.tvGender);
        tvClass = findViewById(R.id.tvClass);
        tvCompany = findViewById(R.id.tvCompany);
        tvDOB = findViewById(R.id.tvDOB);
        tvAddress = findViewById(R.id.tvAddress);
        btnSaveEnable = findViewById(R.id.btnSaveEnable);
        btnSaveDisable = findViewById(R.id.btnSaveDisable);
        tvName = findViewById(R.id.tvName);
        tvNoPeg = findViewById(R.id.tvUID);
        tvEmail = findViewById(R.id.tvEmail);
        tvHp = findViewById(R.id.tvHp);
        tvNIP = findViewById(R.id.tvNIP);
        tvDivision = findViewById(R.id.tvDivision);
        userProfileImage = findViewById(R.id.profile_image);
        progressTxt = findViewById(R.id.progressTxt);
        progressUpload = findViewById(R.id.progressBar_profil);
    }

    public String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    private void showDateDialog(){
        Calendar newCalendar = Calendar.getInstance();

        datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                NumberFormat formatter = new DecimalFormat("00");

                StringBuilder str = new StringBuilder();
                str.append(formatter.format(dayOfMonth));
                str.append(" - ");
                str.append(formatter.format(monthOfYear + 1));
                str.append(" - ");
                str.append(year);

                tvDOB.setText(str.toString());
                checkForm();
            }

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

        datePickerDialog.show();
    }

    private void checkForm(){
        if(!tvName.getText().equals("") && !tvDOB.getText().equals("") && !tvGender.getText().equals("") && !tvClass.getText().equals("") &&
        !tvCompany.getText().equals("") && !tvHp.getText().equals("") && !tvDivision.getText().equals("") && !tvName.getText().equals("-") &&
                !tvDOB.getText().equals("-") && !tvGender.getText().equals("-") && !tvClass.getText().equals("-") && !tvCompany.getText().equals("-") &&
                !tvHp.getText().equals("-") && !tvDivision.getText().equals("-") && tvHp.getText().length() > 2 && tvNIP.getText().length() > 2 &&
        tvName.getText().length() > 2 && tvAddress.getText().length() > 2){
            btnSaveEnable.setVisibility(View.VISIBLE);
            btnSaveDisable.setVisibility(View.GONE);
            Log.d("CEK", "AA");
            Log.d("CEK", tvHp.getText().toString());
        }
        else
        {
            btnSaveEnable.setVisibility(View.GONE);
            btnSaveDisable.setVisibility(View.VISIBLE);
            Log.d("CEK", "BB");
        }
    }

    private void addCam(){
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "New Picture");
        values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
        media_camera = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, media_camera);
        startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
    }

    private void addPic() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture(s)"), PICK_IMAGE_INTENT);
    }

    private void retrieveInfo(){
        tvName.setText(userFirebase.getDisplayName());
        Picasso.get().load(userFirebase.getPhotoUrl()).placeholder(R.drawable.employee_img).into(userProfileImage);
        tvNoPeg.setText(googleLogin.getId());
        tvEmail.setText(googleLogin.getEmail());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String userId = userFirebase.getUid();

        if(requestCode == PICK_IMAGE_INTENT)
        {
            if(resultCode == RESULT_OK){
                Uri resultUri = data.getData();

                StorageReference filePath = UserProfileImgRef.child(userId + ".jpg");
                progressUpload.setVisibility(View.VISIBLE);
                progressUpload.setIndeterminate(false);

                filePath.putFile(resultUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                        double progress = (100 * snapshot.getBytesTransferred()) / snapshot.getTotalByteCount();
                        progressUpload.setProgress((int) progress);
                        progressTxt.setText(progress + " %");
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        final Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl();
                        firebaseUri.addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                final String downloadUrl = uri.toString();
                                // complete the rest of your code
                                userRef.child(userId).child("image")
                                        .setValue(downloadUrl)
                                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if(task.isSuccessful()){
                                                    Toast toast = Toast.makeText(CreateUser.this,
                                                            "Foto telah disimpan",
                                                            Toast.LENGTH_SHORT);

                                                    View toastView = toast.getView();
                                                    toastView.setBackgroundResource(R.drawable.toast_drawable);
                                                    toast.show();
                                                    progressTxt.append(" File Uploaded");
                                                    finish();
                                                    startActivity(getIntent());
                                                }
                                                else
                                                {
                                                    String message = task.getException().toString();
                                                    Toast toast = Toast.makeText(CreateUser.this,
                                                            "Error: " + message,
                                                            Toast.LENGTH_SHORT);

                                                    View toastView = toast.getView();
                                                    toastView.setBackgroundResource(R.drawable.toast_drawable);
                                                    toast.show();
                                                }
                                            }
                                        });

                            }
                        });

                    }
                });
            }
        }
        else if(requestCode == IMAGE_CAPTURE_CODE){//Camera
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if(resultCode == RESULT_OK)
            {
                Uri resultUri = media_camera;

                StorageReference filePath = UserProfileImgRef.child(userId + ".jpg");
                progressUpload.setVisibility(View.VISIBLE);
                progressUpload.setIndeterminate(false);

                filePath.putFile(resultUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                        double progress = (100 * snapshot.getBytesTransferred()) / snapshot.getTotalByteCount();
                        progressUpload.setProgress((int) progress);
                        progressTxt.setText(progress + " %");
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        final Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl();
                        firebaseUri.addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                final String downloadUrl = uri.toString();
                                // complete the rest of your code
                                userRef.child(userId).child("image")
                                        .setValue(downloadUrl)
                                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if(task.isSuccessful()){
                                                    Toast toast = Toast.makeText(CreateUser.this,
                                                            "Foto telah disimpan",
                                                            Toast.LENGTH_SHORT);

                                                    View toastView = toast.getView();
                                                    toastView.setBackgroundResource(R.drawable.toast_drawable);
                                                    toast.show();
                                                    progressTxt.append(" File Uploaded");
                                                    finish();
                                                    startActivity(getIntent());
                                                }
                                                else
                                                {
                                                    String message = task.getException().toString();
                                                    Toast.makeText(CreateUser.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });

                            }
                        });

                    }
                });
            }
        }
    }

    private void updateUser(){
        String userId = userFirebase.getUid();
        String setUserName = tvName.getText().toString();
        String setnoPeg = tvNoPeg.getText().toString();
        String setJabatan = tvJabatan.getText().toString();
        String setEmail = userFirebase.getEmail();
        String setHp = tvHp.getText().toString();
        String setLokasi = tvLokasi.getText().toString();

        if(TextUtils.isEmpty(setUserName) || TextUtils.isEmpty(setnoPeg) || TextUtils.isEmpty(setJabatan) || TextUtils.isEmpty(setHp) || TextUtils.isEmpty(setLokasi) || TextUtils.isEmpty(setEmail))
            Toast.makeText(this, "Mohon lengkapi data anda", Toast.LENGTH_SHORT).show();
        else
        {
            try {
                userRef.child(userId).child("uid").setValue(userId);
                userRef.child(userId).child("namaLengkap").setValue(setUserName);
                userRef.child(userId).child("noPeg").setValue(setnoPeg);
                userRef.child(userId).child("jabatan").setValue(setJabatan);
                userRef.child(userId).child("noHp").setValue(setHp);
                userRef.child(userId).child("email").setValue(setEmail);
                userRef.child(userId).child("penempatan").setValue(setLokasi);
                userRef.child(userId).child("deviceId").setValue(getDeviceName());
                Toast.makeText(getBaseContext(), "Profil telah diperbarui", Toast.LENGTH_SHORT).show();
//                toHomeActivity();
//                profileMap = new HashMap<>();
//                profileMap.put("uid", userId);
//                profileMap.put("namaLengkap", setUserName);
//                profileMap.put("noPeg", setnoPeg);
//                profileMap.put("jabatan", setJabatan);
//                profileMap.put("noHp", setHp);
//                profileMap.put("email", setEmail);
//                profileMap.put("penempatan", setLokasi);
//                profileMap.put("deviceId", getDeviceName());
//                userRef.child(userId).setValue(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
//                    @Override
//                    public void onComplete(@NonNull Task<Void> task) {
//                        if(task.isSuccessful()) {
//                            profileMap.clear();
//                            Toast.makeText(getBaseContext(), "Profil telah diperbarui", Toast.LENGTH_SHORT).show();
//                            toHomeActivity();
//                        }
//                        else
//                        {
//                            String message = task.getException().toString();
//                            Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
//                        }
//                    }
//                });
            }catch (Exception e){
                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
            }

        }
    }

//    private void toHomeActivity(){
//        Intent homeIntent = new Intent(CreateUser.this, Home.class);
//        homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        startActivity(homeIntent);
//        finish();
//    }

    private String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    private void getWriteStorage(){
        String[] permission = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                WRITE_STORAGE) == PackageManager.PERMISSION_GRANTED){
            mWriteExternalStorage = true;
        }else{
            ActivityCompat.requestPermissions(this, permission,
                    STORAGE_PERMISSION_REQUEST_CODE);
        }
    }

    private void getCameraPermission(){

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                CAMERA_USAGE) == PackageManager.PERMISSION_GRANTED){
            mCameraPermission = true;
        }else{
            ActivityCompat.requestPermissions(this, new String[] {CAMERA_USAGE},
                    CAMERA_PERMISSION_REQUEST_CODE);
        }
    }
}