package com.project.ilsaenterprise.monitoring;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
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.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.project.ilsaenterprise.Home;
import com.project.ilsaenterprise.R;
import com.project.ilsaenterprise.adapter.MediaAdapter;
import com.project.ilsaenterprise.models.Employees;
import com.theartofdev.edmodo.cropper.CropImage;
import com.thekhaeng.pushdownanim.PushDownAnim;
import com.google.android.gms.tasks.OnSuccessListener;
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.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class Upload extends AppCompatActivity {

    private static final int IMAGE_CAPTURE_CODE = 101;
    private EditText edtDistrik, edtKebun, edtAfdeling, edtLaporan, edtJenis;
    private static final String TAG = "Upload";
    private String[] kebunD1, kebunD2, kebunD3, kebunD4, distrik, afdeling, jenisLaporan, hama, penyakit, jalan, TM, TBM, curi, lainnya;
    private String textTmp;
    private ArrayAdapter<String> arrayAdapter_farm, arrayAdapter_tLap;
    private RelativeLayout btnUpload;
    private com.getbase.floatingactionbutton.FloatingActionButton btnAddCam, btnAddGallery;
    private RecyclerView mMedia;
    private RecyclerView.Adapter mMediaAdapter;
    private RecyclerView.LayoutManager mMediaLayoutManager;
    Task location;
    FusedLocationProviderClient mFusedLocationProviderClient;
    Location currentLocation;
    double latitude, longitude;
    private Boolean mLocationPermissionsGranted = false;
    private Boolean mWriteExternalStorage = false;
    private Boolean mCameraPermission = false;
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    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 static final int PLAY_SERVICE_RESOLUTION_REQUEST = 4799;
    ProgressDialog progressDialog;
    private int upload_count = 0;
    int totalMediaUploaded = 0;
    private List<String> fileNameList;
    private HashMap<Object, String> monitoringMap = new HashMap<>();
    private String check;
    private EditText posting, blok;
    final String[] selectedDistrict = new String[1];
    final String[] selectedFarm = new String[1];
    final String[] selectedAfd = new String[1];
    final String[] selectedJenisLaporan = new String[1];
    final String[] selectedLaporan = new String[1];
    int PICK_IMAGE_INTENT = 1;
    ArrayList<String> mediaUriList = new ArrayList<>();
    ArrayList<String> mediaIdList = new ArrayList<>();
    Uri media_camera;
    private GoogleSignInAccount googleLogin;
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;
    private DatabaseReference reference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.Dark));
        setContentView(R.layout.activity_upload);
        getSupportActionBar().hide();

        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        mAuth = FirebaseAuth.getInstance();
        userFirebase = mAuth.getCurrentUser();
        reference = FirebaseDatabase.getInstance().getReference().child("users").child(userFirebase.getUid());

        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        btnAddCam = findViewById(R.id.bt_Add);
        btnAddGallery = findViewById(R.id.addPhotoGalery);
        edtDistrik = findViewById(R.id.edtDistrict);
        edtKebun = findViewById(R.id.edtKebun);
        edtAfdeling = findViewById(R.id.edtAfdeling);
        edtLaporan = findViewById(R.id.edtTipe);
        edtJenis = findViewById(R.id.edtJenis);
        posting = findViewById(R.id.posting_txt);
        blok = findViewById(R.id.blok_txt);
        edtDistrik.setEnabled(true);
        edtKebun.setEnabled(false);
        edtAfdeling.setEnabled(false);
        edtLaporan.setEnabled(false);
        edtJenis.setEnabled(false);

        getLocationPermission();
        getDeviceLocation();

        mediaUriList.clear();
        PushDownAnim.setPushDownAnimTo(btnAddCam).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    getWriteStorage();
                    getCameraPermission();
                    if(mWriteExternalStorage == true && 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();
                }

                //New activity get image
//                startActivity(new Intent(Upload.this, SelectImage.class));
            }
        });

        initializeMedia();
        fileNameList = new ArrayList<>();

        String currentDate = new SimpleDateFormat("dd MMMM yyyy", Locale.getDefault()).format(new Date());
        final String currentTime = new SimpleDateFormat("HH.mm", Locale.getDefault()).format(new Date()) + " WIB";

        final DatabaseReference newMonit = FirebaseDatabase.getInstance().getReference("monitoring");
        final Map newMessageMap = new HashMap<>();
        final HashMap<Object, String> map = new HashMap<>();

        edtDistrik.setFocusable(false);
        edtDistrik.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog(R.layout.layout_popup_selected, "Distrik", distrik);
                edtKebun.setEnabled(true);
            }
        });

        edtKebun.setFocusable(false);
        edtKebun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("EDIT", edtDistrik.getText().toString());
                if(edtDistrik.getText().toString().equals(distrik[0]))
                    showAlertDialog(R.layout.layout_popup_selected, "Kebun", kebunD1);
                else if(edtDistrik.getText().toString().equals(distrik[1]))
                    showAlertDialog(R.layout.layout_popup_selected, "Kebun", kebunD2);
                else if(edtDistrik.getText().toString().equals(distrik[2]))
                    showAlertDialog(R.layout.layout_popup_selected, "Kebun", kebunD3);
                else if(edtDistrik.getText().toString().equals(distrik[3]))
                    showAlertDialog(R.layout.layout_popup_selected, "Kebun", kebunD4);

                edtAfdeling.setEnabled(true);
            }
        });

        edtAfdeling.setFocusable(false);
        edtAfdeling.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog(R.layout.layout_popup_selected, "Afdeling", afdeling);
                edtLaporan.setEnabled(true);
            }
        });

        edtLaporan.setFocusable(false);
        edtLaporan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog(R.layout.layout_popup_selected, "Laporan", jenisLaporan);
                edtJenis.setEnabled(true);
            }
        });

        edtJenis.setFocusable(false);
        edtJenis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(edtLaporan.getText().toString().equals(jenisLaporan[0]))
                    showAlertDialog(R.layout.layout_popup_selected, "Jenis Laporan", TM);
                else if(edtLaporan.getText().toString().equals(jenisLaporan[1]))
                    showAlertDialog(R.layout.layout_popup_selected, "Jenis Laporan", TBM);
                else if(edtLaporan.getText().toString().equals(jenisLaporan[2]))
                    showAlertDialog(R.layout.layout_popup_selected, "Jenis Laporan", jalan);
                else if(edtLaporan.getText().toString().equals(jenisLaporan[3]))
                    showAlertDialog(R.layout.layout_popup_selected, "Jenis Laporan", hama);
                else if(edtLaporan.getText().toString().equals(jenisLaporan[4]))
                    showAlertDialog(R.layout.layout_popup_selected, "Jenis Laporan", penyakit);
                else if(edtLaporan.getText().toString().equals(jenisLaporan[5]))
                    edtJenis.setText("Pencurian");
                else if(edtLaporan.getText().toString().equals(jenisLaporan[6]))
                    edtJenis.setText("Lainnya");
            }
        });

        final String userID = userFirebase.getUid();

        btnUpload = findViewById(R.id.btnUpload);
        PushDownAnim.setPushDownAnimTo(btnUpload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog.show();
                progressDialog.setTitle("Mengunggah Data");
                check = "";


                final String[] postingEdit = new String[1];
                final String[] blokEdit = new String[1];

                final String timeStamp = String.valueOf(System.currentTimeMillis());
                int position = 0;
                if(TextUtils.isEmpty(edtDistrik.getText())){
                    Toast.makeText(Upload.this, "Distrik tidak boleh kosong", Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();
                    return;
                }
                if(TextUtils.isEmpty(edtAfdeling.getText())){
                    Toast.makeText(Upload.this, "Afdeling tidak boleh kosong", Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();
                    return;
                }
                if(TextUtils.isEmpty(edtLaporan.getText())){
                    Toast.makeText(Upload.this, "Laporan tidak boleh kosong", Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();
                    return;
                }
                if(TextUtils.isEmpty(posting.getText().toString())){
                    posting.setError("Silahkan masukkan deskripsi laporan");
                    progressDialog.dismiss();
                    return;
                }
                if(TextUtils.isEmpty(blok.getText().toString())){
                    blok.setError("Silahkan masukkan lokasi blok");
                    progressDialog.dismiss();
                    return;
                }
                if(mediaUriList.isEmpty()){
                    Toast.makeText(Upload.this, "Masukkan dokumentasi foto", Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();
                    return;
                }

                if(latitude != 0.0 && longitude != 0.0){
                    reference.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            Employees employees = dataSnapshot.getValue(Employees.class);
                            check = reference.push().getKey();
                            selectedDistrict[0] = edtDistrik.getText().toString();
                            selectedAfd[0] = edtAfdeling.getText().toString();
                            selectedFarm[0] = edtKebun.getText().toString();
                            selectedJenisLaporan[0] = edtJenis.getText().toString();
                            selectedLaporan[0] = edtLaporan.getText().toString();
                            postingEdit[0] = posting.getText().toString();
                            blokEdit[0] = blok.getText().toString();

                            monitoringMap.put("uid", userID);
                            monitoringMap.put("fullName", employees.getNamaLengkap());
                            monitoringMap.put("district", selectedDistrict[0]);
                            monitoringMap.put("farm", selectedFarm[0]);
                            monitoringMap.put("afdeling", selectedAfd[0]);
                            monitoringMap.put("jabatan", employees.getJabatan());
                            monitoringMap.put("deskripsi", postingEdit[0]);
                            monitoringMap.put("jenisLaporan", selectedJenisLaporan[0]);
                            monitoringMap.put("tipeLaporan", selectedLaporan[0]);
                            monitoringMap.put("uploadDate",  currentDate);
                            monitoringMap.put("uploadTime", currentTime);
                            monitoringMap.put("blok", blokEdit[0]);
                            monitoringMap.put("timestamp", timeStamp);
                            monitoringMap.put("latitude", String.valueOf(latitude));
                            monitoringMap.put("longitude", String.valueOf(longitude));
                            //monitoringMap.put( new dataMonitoring(employees.getNamaLengkap(), selectedAfd[0], selectedDistrict[0], selectedFarm[0],  postingEdit[0], employees.getJabatan()));
                            newMonit.child(timeStamp).setValue(monitoringMap);

                            if(!mediaUriList.isEmpty()){
                                int uploaded = 0;
                                for(String mediaUri : mediaUriList){
                                    progressDialog.setMessage("Uploading " + uploaded + " / " + mediaUriList.size());
                                    String mediaId = newMonit.child(timeStamp).child("media").push().getKey();
                                    mediaIdList.add(mediaId);

                                    final StorageReference filepath = FirebaseStorage.getInstance().getReference().child("farmMonitoring").child(mediaId);

                                    UploadTask uploadTask = filepath.putFile(Uri.parse(mediaUri));

                                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                        @Override
                                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                            filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                                @Override
                                                public void onSuccess(Uri uri) {
                                                    if(totalMediaUploaded == 0){
                                                        String id = String.valueOf(totalMediaUploaded);
                                                        newMessageMap.put("/imageUrl/", uri.toString());
                                                        newMessageMap.put("/media/" + mediaIdList.get(totalMediaUploaded) + "/link/", uri.toString());
                                                        totalMediaUploaded++;
                                                        if(totalMediaUploaded == mediaUriList.size()){
                                                            newMonit.child(timeStamp).updateChildren(newMessageMap);
                                                        }
                                                    }else{
                                                        String id = String.valueOf(totalMediaUploaded);
                                                        //newMessageMap.put("/media/" + id, uri.toString());
                                                        newMessageMap.put("/media/" + mediaIdList.get(totalMediaUploaded) + "/link/", uri.toString());
                                                        totalMediaUploaded++;
                                                        if(totalMediaUploaded == mediaUriList.size()){
                                                            newMonit.child(timeStamp).updateChildren(newMessageMap);
                                                        }
                                                    }

                                                }
                                            });
                                        }
                                    });
                                    uploaded++;

                                }
                                if(uploaded == mediaUriList.size()){
                                    progressDialog.dismiss();
                                    Toast.makeText(Upload.this, "Upload File Selesai",
                                            Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(Upload.this, Home.class);
                                    startActivity(intent);
                                }
                            }else{
                                //tambah deskrip
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            System.out.println("The read failed: " + databaseError.getCode());
                            progressDialog.dismiss();
                        }
                    });
                }//GEO TAG NOT FOUND
                else{
                    getLocationPermission();
                }
            }
        });

        final Resources res = getResources();
        kebunD1 = res.getStringArray(R.array.kebun_distrik_1);
        kebunD2 = res.getStringArray(R.array.kebun_distrik_2);
        kebunD3 = res.getStringArray(R.array.kebun_distrik_3);
        kebunD4 = res.getStringArray(R.array.kebun_distrik_4);
        distrik = res.getStringArray(R.array.distrik);
        afdeling = res.getStringArray(R.array.afdeling);
        jenisLaporan = res.getStringArray(R.array.jenisLapor);
        hama = res.getStringArray(R.array.Hama);
        penyakit = res.getStringArray(R.array.Penyakit);
        jalan = res.getStringArray(R.array.Jalan);
        curi = res.getStringArray(R.array.curi);
        lainnya = res.getStringArray(R.array.lainnya);
        TM = res.getStringArray(R.array.TM);
        TBM = res.getStringArray(R.array.TBM);

        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, distrik);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spinnerDis.setAdapter(adapter1);
//
//        spinnerDis.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//
//                if(position == 0){
//                    spinnerKeb.setEnabled(false);
//                    spinnerAfd.setEnabled(false);
//                }
//                else if(position==1)
//                {
//                    spinnerKeb.setEnabled(true);
//                    arrayAdapter_farm = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, kebunD1);
//                }
//                else if(position==2)
//                {
//                    spinnerKeb.setEnabled(true);
//                    arrayAdapter_farm = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, kebunD2);
//                }
//                else if(position==3)
//                {
//                    spinnerKeb.setEnabled(true);
//                    arrayAdapter_farm = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, kebunD3);
//                }
//                else if(position==4)
//                {
//                    spinnerKeb.setEnabled(true);
//                    arrayAdapter_farm = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, kebunD4);
//                }
//                spinnerKeb.setAdapter(arrayAdapter_farm);
//            }
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });

//        spinnerKeb.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                if(position > 0){
//                    spinnerAfd.setEnabled(true);
//                }
//            }
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                return;
//            }
//        });



//        spinnerAfd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                if(position > 0){
//                    spinnerJLap.setEnabled(true);
//                }
//            }
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                return;
//            }
//        });
//
//        spinnerJLap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                if(position == 0){
//                    spinnerTLap.setEnabled(false);
//                }
//                else if(position == 1){
//                    arrayAdapter_tLap = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, TM);
//                    spinnerTLap.setAdapter(arrayAdapter_tLap);
//                    spinnerTLap.setEnabled(true);
//                }
//                else if(position == 2){
//                    arrayAdapter_tLap = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, TBM);
//                    spinnerTLap.setAdapter(arrayAdapter_tLap);
//                    spinnerTLap.setEnabled(true);
//                }
//                else if(position == 3){
//                    arrayAdapter_tLap = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, jalan);
//                    spinnerTLap.setAdapter(arrayAdapter_tLap);
//                    spinnerTLap.setEnabled(true);
//                }
//                else if(position == 4){
//                    arrayAdapter_tLap = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, hama);
//                    spinnerTLap.setAdapter(arrayAdapter_tLap);
//                    spinnerTLap.setEnabled(true);
//                }
//                else if(position == 5){
//                    arrayAdapter_tLap = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, penyakit);
//                    spinnerTLap.setAdapter(arrayAdapter_tLap);
//                    spinnerTLap.setEnabled(true);
//                }
//                else if(position == 6){
//                    arrayAdapter_tLap = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, curi);
//                    selectedLaporan[0] = spinnerJLap.getSelectedItem().toString();
//                    spinnerTLap.setAdapter(arrayAdapter_tLap);
//                    spinnerTLap.setEnabled(false);
//                }
//                else if(position == 7){
//                    arrayAdapter_tLap = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, lainnya);
//                    selectedLaporan[0] = spinnerJLap.getSelectedItem().toString();
//                    spinnerTLap.setAdapter(arrayAdapter_tLap);
//                    spinnerTLap.setEnabled(false);
//                }
//            }
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                return;
//            }
//        });
    }

    private String showAlertDialog(int layout, String selection, String[] SelectionArr){
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Upload.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> listDistrict = new ArrayList<>(Arrays.asList(SelectionArr));

        ListView lvDistrict = 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, listDistrict);
        lvDistrict.setAdapter(arrayAdapter);

        final String[] selected = {""};
        lvDistrict.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("Distrik")){
                     edtDistrik.setText(selected[0]);
                     edtKebun.setText(null);
                 }
                 else if (selection.equals("Kebun")){
                     edtKebun.setText(selected[0]);
                 }
                 else if (selection.equals("Afdeling")){
                     edtAfdeling.setText(selected[0]);
                 }
                 else if (selection.equals("Laporan")){
                     edtLaporan.setText(selected[0]);
                 }
                 else if (selection.equals("Jenis Laporan")){
                     edtJenis.setText(selected[0]);
                 }


                alertDialog.cancel();
            }
        });

        return selectedDistrict[0];
    }

    private void getDeviceLocation(){
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        try{
            if(mLocationPermissionsGranted){
                location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful() && task.getResult() != null){
                            currentLocation = (Location) task.getResult();

                            Log.d(TAG, "onComplete: found location!");

                            latitude = currentLocation.getLatitude();
                            longitude = currentLocation.getLongitude();

                        } else{
                            mFusedLocationProviderClient.getLastLocation();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void getLocationPermission(){
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            {
                mLocationPermissionsGranted = true;
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

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

    public String getFileName(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    //result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } finally {
                cursor.close();
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

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

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == PICK_IMAGE_INTENT){//Galery
            if(resultCode == RESULT_OK){
                if(data.getClipData() == null){
                    mediaUriList.add(data.getData().toString());
                }
                else{
                    for(int i = 0; i < data.getClipData().getItemCount(); i++){
                        mediaUriList.add(data.getClipData().getItemAt(i).getUri().toString());
                    }
                }
                mMediaAdapter.notifyDataSetChanged();
            }
        }
        else if(requestCode == IMAGE_CAPTURE_CODE){//Camera
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if(resultCode == RESULT_OK)
            {
                mediaUriList.add(media_camera.toString());
                mMediaAdapter.notifyDataSetChanged();
            }
        }
    }

    @SuppressLint("WrongConstant")
    private void initializeMedia() {
        mediaUriList = new ArrayList<>();
        mMedia = findViewById(R.id.mediaList);
        mMedia.setNestedScrollingEnabled(false);
        mMedia.setHasFixedSize(false);
        mMediaLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.HORIZONTAL, false);
        mMedia.setLayoutManager(mMediaLayoutManager);
        mMediaAdapter = new MediaAdapter(getApplicationContext(), mediaUriList);
        mMedia.setAdapter(mMediaAdapter);
    }
}
