package com.project.ilsaenterprise;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
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.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
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.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;
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.adapter.MediaAdapter;
import com.thekhaeng.pushdownanim.PushDownAnim;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class KirimData extends AppCompatActivity {
    private static final int REQUEST_GET_SINGLE_FILE = 101;
    private static final int REQUEST_GET_MULTI_FILE = 102;
    private Button btnCancel, btnSave, btnAddData, btnAddImage, btnAddPdf, btnAddExcel, btnAddWord;
    //private FirebaseAuth mAuth;
    private FirebaseStorage firebaseStorage;
    private DatabaseReference dataRef;
    private RelativeLayout relAdapter;
    private LinearLayout linearLayoutGone;
    private RecyclerView mMedia;
    private RecyclerView.Adapter mMediaAdapter;
    private RecyclerView.LayoutManager mMediaLayoutManager;
    Uri pdfUri, wordUri, excelUri, kmlUri;
    private String dataPilih;
    private EditText judulEdit, deskripsiEdit;
    ArrayList<String> mediaUriList = new ArrayList<>();
    int PICK_DATA_INTENT = 1;
    private HashMap<Object, String> uploadMap = new HashMap<>();
    ProgressDialog progressDialog;
    final Map urlMap = new HashMap<>();
    FirebaseFirestore db;
    String userUpload, extUpload;
    private DatabaseReference userRef;
    private TextView userTxt;
    private GoogleSignInAccount googleLogin;

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

        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());

        btnCancel = findViewById(R.id.btnCancel);
        btnSave = findViewById(R.id.btnSave);
        btnAddData = findViewById(R.id.btnAddData);
        btnCancel.setBackgroundColor(Color.TRANSPARENT);
        btnSave.setBackgroundColor(Color.TRANSPARENT);
        relAdapter = findViewById(R.id.relativeLayoutAdapter);
        linearLayoutGone = findViewById(R.id.LinearIntroGone);
        judulEdit = findViewById(R.id.judulEdit);
        deskripsiEdit = findViewById(R.id.deskripsiEdit);
        userTxt = findViewById(R.id.userTxtLaporan);
//        tambah file
        mediaUriList = new ArrayList<>();
        mMedia = findViewById(R.id.FileList);
        mMedia.setNestedScrollingEnabled(false);
        mMedia.setHasFixedSize(false);
        mMediaLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.HORIZONTAL, false);
        mMedia.setLayoutManager(mMediaLayoutManager);
        mMediaAdapter = new MediaAdapter(getApplicationContext(), mediaUriList);
        mMedia.setAdapter(mMediaAdapter);

        //mAuth = FirebaseAuth.getInstance();
        firebaseStorage = FirebaseStorage.getInstance();
        dataRef = FirebaseDatabase.getInstance().getReference();
        db = FirebaseFirestore.getInstance();
        userRef = FirebaseDatabase.getInstance().getReference().child("users");

        retrieveData();

        PushDownAnim.setPushDownAnimTo(btnAddData).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ContextCompat.checkSelfPermission(KirimData.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
                {
                    showAlertDialog(R.layout.layout_popup_jenisfile);
                }else {
                    ActivityCompat.requestPermissions(KirimData.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 9);
                }
            }
        });

        PushDownAnim.setPushDownAnimTo(btnCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(KirimData.this, WorkFromHome.class);
                startActivity(intent);
                finish();
            }
        });

        PushDownAnim.setPushDownAnimTo(btnSave).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(pdfUri != null){{
                    uploadFile(pdfUri);
                }
                }else
                    Toast.makeText(KirimData.this, "Silahkan masukkan Data terlebih dahulu", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void retrieveData(){
        //userUpload = googleLogin.getId();
        userTxt.setText(googleLogin.getId());
    }

    private void uploadFile(Uri pdfUri) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("Mengunggah File...");
        progressDialog.show();
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();
        String uid = googleLogin.getId();
        String fileName = judulEdit.getText().toString();
        String deskripsi = deskripsiEdit.getText().toString();
        final StorageReference storageReference = firebaseStorage.getReference().child("UploadWFH").child(fileName);
        UploadTask uploadTask = storageReference.putFile(pdfUri);

        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        uploadMap.put("uid", uid);
                        uploadMap.put("nama", userTxt.getText().toString());
                        uploadMap.put("fileName", fileName);
                        uploadMap.put("timestamp", ts);
                        uploadMap.put("ekstensi", extUpload);
                        uploadMap.put("url", uri.toString());
                        uploadMap.put("deskripsi", deskripsi);
                        dataRef.child("UploadWfh").child(ts).setValue(uploadMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()) {
                                    Toast.makeText(KirimData.this, "File Telah di-Upload", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(KirimData.this, WorkFromHome.class);
                                    startActivity(intent);
                                    finish();
                                }
                                else
                                    Toast.makeText(KirimData.this, "File Gagal di-Upload", Toast.LENGTH_SHORT).show();
                            }
                        });

                        Map<String, Object> todo = new HashMap<>();

                        todo.put("user_id", uid);
                        todo.put("title", fileName);
                        todo.put("desc", deskripsi);
                        todo.put("timestamp", ts);

                        db.collection("EndTodo").document(uid).collection("Laporan")
                                .document(ts)
                                .set(todo).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                db.collection("ToDoList")
                                        .document(uid).collection("Laporan")
                                        .document(ts)
                                        .delete()
                                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {
                                                Toast.makeText(KirimData.this, "Task Selesai", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            }
                        });
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(KirimData.this, "File Gagal di-Upload", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                int currentProgress = (int) (100 * snapshot.getBytesTransferred()/snapshot.getTotalByteCount());
                progressDialog.setProgress(currentProgress);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 9 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            showAlertDialog(R.layout.layout_popup_jenisfile);
        } else
            Toast.makeText(KirimData.this, "Izinkan Aplikasi untuk mengakses penyimpanan", Toast.LENGTH_LONG).show();
    }


    private void showAlertDialog(int layout){
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(KirimData.this);
        View layoutView = getLayoutInflater().inflate(layout, null);
        //Button dialogButton = layoutView.findViewById(R.id.btnDialog);
        CardView btnPdf, btnImage, btnDrone, btnWord, btnExcel, btnKml;
        btnPdf = layoutView.findViewById(R.id.btnAddPdf);
        btnImage = layoutView.findViewById(R.id.btnAddImage);
        btnDrone = layoutView.findViewById(R.id.btnAddImageDrone);
        btnWord = layoutView.findViewById(R.id.btnAddWord);
        btnExcel = layoutView.findViewById(R.id.btnAddExcel);
        btnKml = layoutView.findViewById(R.id.btnAddKml);

        dialogBuilder.setView(layoutView);
        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        alertDialog.show();
        dataPilih = "";
        extUpload = "";
        btnPdf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                String[] mimeTypes = {"application/pdf"};
                intent.setType("*/*");
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                startActivityForResult(Intent.createChooser(intent, "Pilih File PDF"), REQUEST_GET_SINGLE_FILE);
                dataPilih = "PDF";
                extUpload = "pdf";
                judulEdit.setEnabled(true);
                deskripsiEdit.setEnabled(true);
                alertDialog.dismiss();
            }
        });

        btnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                intent.setAction(intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Pilih Gambar (Maks 5)"), REQUEST_GET_MULTI_FILE);
                deskripsiEdit.setEnabled(true);
                dataPilih = "Image";
                btnAddData.setVisibility(View.INVISIBLE);
                linearLayoutGone.setVisibility(View.INVISIBLE);
                relAdapter.setVisibility(View.VISIBLE);
                alertDialog.dismiss();
            }
        });

        btnDrone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                intent.setAction(intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Pilih Gambar (Maks 5)"), REQUEST_GET_SINGLE_FILE);
                dataPilih = "Drone";
                deskripsiEdit.setEnabled(true);
                btnAddData.setVisibility(View.INVISIBLE);
                linearLayoutGone.setVisibility(View.INVISIBLE);
                relAdapter.setVisibility(View.VISIBLE);
                alertDialog.dismiss();
            }
        });

        btnWord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                String[] mimeTypes = {"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"};
                intent.setType("*/*");
                dataPilih = "Word";
                extUpload = "docx";
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                startActivityForResult(Intent.createChooser(intent, "Pilih File Word"), REQUEST_GET_SINGLE_FILE);
                judulEdit.setEnabled(true);
                deskripsiEdit.setEnabled(true);
                alertDialog.dismiss();
            }
        });

        btnExcel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                String[] mimeTypes = {"application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
                intent.setType("*/*");
                dataPilih = "Excel";
                extUpload = "xlsx";
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                startActivityForResult(Intent.createChooser(intent, "Pilih File Excel"), REQUEST_GET_SINGLE_FILE);
                judulEdit.setEnabled(true);
                deskripsiEdit.setEnabled(true);
                alertDialog.dismiss();
            }
        });

        btnKml.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                String[] mimeTypes = {"application/vnd.google-earth.kml+xml"};
                intent.setType("*/*");
                dataPilih = "Kml";
                extUpload = "kml";
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                startActivityForResult(Intent.createChooser(intent, "Pilih File Kml"), REQUEST_GET_SINGLE_FILE);
                judulEdit.setEnabled(true);
                deskripsiEdit.setEnabled(true);
                alertDialog.dismiss();
            }
        });

    }

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

        if(dataPilih == "Image" || dataPilih == "Drone"){
            mediaUriList.clear();
            if(resultCode == RESULT_OK && requestCode == REQUEST_GET_MULTI_FILE){
                if(requestCode == PICK_DATA_INTENT){
                    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 == REQUEST_GET_SINGLE_FILE && resultCode == RESULT_OK && data != null){
                pdfUri = data.getData();
                Toast.makeText(KirimData.this, "File telah dipilih", Toast.LENGTH_SHORT).show();
                //judulEdit.setText(pdfUri.getLastPathSegment());
            }
            else
                Toast.makeText(KirimData.this, "Silahkan masukkan Data terlebih dahulu", Toast.LENGTH_SHORT).show();
        }
    }
}