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.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
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.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
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.Login;
import com.project.ilsaenterprise.R;
import com.project.ilsaenterprise.SharedPref;
import com.project.ilsaenterprise.models.Employees;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.thekhaeng.pushdownanim.PushDownAnim;


import org.w3c.dom.Text;

import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;

public class UserProfile extends AppCompatActivity {

    private static final String TAG = "UserProfil";
    private static final int PICK_IMAGE_INTENT = 1;
    private TextView tvName, tvNoPeg, tvJabatan, tvLokasi, tvEmail, tvHp, tvDOB, tvGender;
    private RelativeLayout updateAccountBtn, editAccountBtn;
    private CircleImageView userProfileImage;
    private 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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.Dark));
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_user_profile);

        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");
        btnAddCam = findViewById(R.id.addCamProfile);
        btnAddGallery = findViewById(R.id.addGalleryProfile);
        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());

        InitializeFields();

        PushDownAnim.setPushDownAnimTo(btnAddCam).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    getWriteStorage();
                    getCameraPermission();
                    if(mCameraPermission == true){
                        addCam();
                    }
                    else
                    {
                        Toast.makeText(getBaseContext(), "Izinkan akses kamera", Toast.LENGTH_SHORT).show();
                        getCameraPermission();
                    }
                }catch(Exception error){
                    Toast.makeText(getBaseContext(), error.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        PushDownAnim.setPushDownAnimTo(btnAddGallery).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getWriteStorage();
                getCameraPermission();
                if(mWriteExternalStorage == true){
                    addPic();
                }
                else
                {
                    Toast.makeText(getBaseContext(), "Izinkan akses galeri", Toast.LENGTH_SHORT).show();
                    getWriteStorage();
                }
            }
        });

        TextView btnChangeName = findViewById(R.id.textView4);
        TextView btnChangePhone = findViewById(R.id.tvPhone);

        btnChangeName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(UserProfile.this, ChangeName.class).putExtra("name", tvName.getText()));
            }
        });

        btnChangePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(UserProfile.this, ChangePhone.class).putExtra("phone", valHp));
            }
        });

        ImageView btnBack = findViewById(R.id.ivBack);

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

//        FloatingActionButton addPhotoFab = findViewById(R.id.fab_camera);
//        addPhotoFab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                Intent galleryIntent = new Intent();
////                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
////                galleryIntent.setType("image/*");
////                startActivityForResult(galleryIntent, GalleryPick);
//                addCam();
//            }
//        });
    }

    @Override
    public void onBackPressed() {
        checkUser();
    }

    public boolean checkUser(){
        DatabaseReference firebaseDatabase = FirebaseDatabase.getInstance().getReference("users");
        FirebaseUser userId = mAuth.getCurrentUser();

        firebaseDatabase.child(userId.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.exists()){
                    startActivity(new Intent(UserProfile.this, Home.class));
                    finish();
                }
                else
                    Toast.makeText(getBaseContext(), "Mohon lengkapi data terlebih dahulu.", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getBaseContext(), "Data Error" + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        return true;
    }

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

        retrieveInfo();
    }

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

    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);
        }
    }

    private void InitializeFields() {
        tvName = findViewById(R.id.nameProfile);
        tvNoPeg = findViewById(R.id.noPegawai);
        tvJabatan = findViewById(R.id.jabatanProfile);
        tvLokasi = findViewById(R.id.lokasiProfile);
        tvEmail = findViewById(R.id.emailProfile);
        tvDOB = findViewById(R.id.tvDOB);
        tvGender = findViewById(R.id.tvGender);
        tvHp = findViewById(R.id.hpProfile);
        userProfileImage = (CircleImageView) findViewById(R.id.profile_image);
        progressTxt = (TextView) findViewById(R.id.progressTxt);
        progressUpload = (ProgressBar) findViewById(R.id.progressBar_profil);
    }

    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);
    }


    @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(UserProfile.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(UserProfile.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(UserProfile.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(UserProfile.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 retrieveInfo(){
        String userId = userFirebase.getUid();
        tvEmail.setText(userFirebase.getEmail());
        tvName.setText(userFirebase.getDisplayName());
        tvHp.setText(userFirebase.getPhoneNumber());
        tvNoPeg.setText(googleLogin.getId());
        Picasso.get().load(userFirebase.getPhotoUrl()).placeholder(R.drawable.employee_img).into(userProfileImage);
        Resources res = getResources();
        String[] company = res.getStringArray(R.array.company);

        userRef.child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.exists()){
                    Employees employees = snapshot.getValue(Employees.class);

                    if(employees.getImage() != null)
                        Picasso.get().load(employees.getImage()).placeholder(R.drawable.employee_img).into(userProfileImage);

                    if(employees.getNamaLengkap() == null || employees.getJabatan() == null){
                        editAccountBtn.setVisibility(View.GONE);
                        updateAccountBtn.setVisibility(View.VISIBLE);
                        Toast.makeText(UserProfile.this, "Mohon lengkapi data anda", Toast.LENGTH_SHORT).show();
                    }
                    if(employees.getNamaLengkap() != null || employees.getJabatan() != null){

                        tvName.setText(employees.getNamaLengkap());
                        tvNoPeg.setText(employees.getNoPeg());
                        tvJabatan.setText(employees.getJabatan());
                        tvLokasi.setText(company[Integer.parseInt(employees.getPerusahaan()) - 1]);
                        tvDOB.setText(snapshot.child("DOB").getValue().toString());
                        tvGender.setText(snapshot.child("gender").getValue().toString());
                        valHp = employees.getNoHp();

                        String tmp = employees.getNoHp();
                        StringBuilder noHp = new StringBuilder();
                        int i = 0, step = 1, step2 = 1;
                        while (i < tmp.length()){
                            if(step == 4 && step2 < 3){
                                noHp.append(tmp.charAt(i));
                                noHp.append(" - ");
                                step = 0;
                                step2++;
                            }
                            else if(step < 4 || step2 == 3){
                                noHp.append(tmp.charAt(i));
                            }
                            step++;
                            i++;
                        }
                        tvHp.setText(noHp.toString());
                    }
                }
            }

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

            }
        });

    }


    private String getIMEINumber() {
        android_id = Settings.Secure.getString(UserProfile.this.getContentResolver(), Settings.Secure.ANDROID_ID);

        return android_id;
    }

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

}
