package com.ttiglobal.inttilectgpchat.blog;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Html;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

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.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.blog.Modal.Blog;
import com.ttiglobal.inttilectgpchat.blog.Modal.Comment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class PostActivity extends AppCompatActivity {

    private Uri post_image_uri;
    private ImageView post_image;
    private EditText post_title, post_details;
    private Button add_post;
    private ProgressDialog pdialog;
    private FirebaseAuth mAuth;
    public static final int PICK_IMAGE = 1;
    private static final int SELECT_VIDEO = 1;
    Boolean option;

    private String selectedVideoPath,filetype,ishoapproved,ishorejected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        mAuth = FirebaseAuth.getInstance();
        TextView header = findViewById(R.id.header);
        Toolbar toolbar = findViewById(R.id.toolbar);
        post_title = findViewById(R.id.post_title);
        post_details = findViewById(R.id.post_details);
        post_image = findViewById(R.id.post_image);
        add_post = findViewById(R.id.add_post_btn);
        Button submit_post_btn = findViewById(R.id.submit_post_btn);

//        header.setText("NEW POST");
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.txt_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);

        ishoapproved = "0";
        ishorejected = "0";

        submit_post_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if((post_image != null) && (post_details!=null) && (post_title != null)){
//                    if (option == false) {
//                        filetype = "1";
//                        uploadPostImage(Html.fromHtml(post_title.getText().toString()).toString());
//                    } else {
////                        filetype = "2";
////                        uploadPostVideo(Html.fromHtml(post_title.getText().toString()).toString());
//                    }
//                }
//                else {
//
//                    Toast.makeText(PostActivity.this, "Fill the details", Toast.LENGTH_LONG).show();
//
//                }
                if (allClear()){
                    filetype = "1";
                    uploadPostImage(Html.fromHtml(post_title.getText().toString()).toString());
                }
            }
        });
        add_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(PostActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(PostActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                    } else {
                        selectImage();
                    }
                } else {
                    selectImage();
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            super.onBackPressed();
        }
        return true;
    }

    private void selectImage() {
        final CharSequence[] options = { "Photo","Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(PostActivity.this);
        builder.setTitle("");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
//                if (options[item].equals("Video")) {
//                    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
//                    startActivityForResult(i, SELECT_VIDEO);
//                    option = true;
//                }
                 if (options[item].equals("Photo")) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(intent, PICK_IMAGE);
                    option = false;
                }
                else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE) {
            if (data != null) {
                post_image_uri = data.getData();
                post_image.setImageURI(post_image_uri);
            } else {
                Toast.makeText(this, "Unable to load Image", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == SELECT_VIDEO) {
            if (resultCode == RESULT_OK) {
                if (selectedVideoPath == null) {
                    Toast.makeText(this, "Unable to load Video", Toast.LENGTH_LONG).show();
                } else {
                    selectedVideoPath = getPath(data.getData());
                    post_image.setImageURI(Uri.parse(selectedVideoPath));
                }
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if(cursor!=null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else return null;
    }

    private void pickimage() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE);
    }

    private boolean allClear() {
        if (post_image_uri == null){
//        if ((post_image_uri == null)|| (selectedVideoPath == null)){
            toast("Please select an Image");
            return false;
        }else if (TextUtils.isEmpty(post_title.getText().toString())){
            post_title.setError("Title can't be Empty");
            return false;
        }else if (TextUtils.isEmpty(post_details.getText().toString())){
            post_details.setError("Detail can't be Empty");
            return false;
        }else {
            return true;
        }
    }

     private void uploadPostImage(final String postId) {
        pdialog = new ProgressDialog(PostActivity.this, R.style.MyAlertDialogStyle);
        pdialog.setMessage("Please wait...");
        pdialog.setIndeterminate(true);
        pdialog.setCanceledOnTouchOutside(false);
        pdialog.setCancelable(false);
        pdialog.show();

        StorageReference riversRef = FirebaseStorage.getInstance().getReference().child("forumimages/" + postId + ".png");
        riversRef.putFile(post_image_uri)
                .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {
                            task.getResult().getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    String imageData = task.getResult().getStorage().getDownloadUrl().toString();
                                    savePostDetails(imageData,uri.toString());
                                }
                            });
                        } else {
                            Toast.makeText(PostActivity.this, "Unable to upload Image ! " + task.getException(), Toast.LENGTH_SHORT).show();
                            pdialog.dismiss();
                        }
                    }
                });
    }

    private void uploadPostVideo(final String postId) {
        pdialog = new ProgressDialog(PostActivity.this, R.style.MyAlertDialogStyle);
        pdialog.setMessage("Please wait...");
        pdialog.setIndeterminate(true);
        pdialog.setCanceledOnTouchOutside(false);
        pdialog.setCancelable(false);
        pdialog.show();

        StorageReference riversRef = FirebaseStorage.getInstance().getReference().child("videos/" + postId + ".mp4");
        riversRef.putFile(post_image_uri)
                .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {
                            task.getResult().getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    String imageData = task.getResult().getStorage().getDownloadUrl().toString();
                                    savePostDetails(imageData,uri.toString());
                                }
                            });
                        } else {
                            Toast.makeText(PostActivity.this, "Unable to upload Image ! " + task.getException(), Toast.LENGTH_SHORT).show();
                            pdialog.dismiss();
                        }
                    }
                });
    }

    private void savePostDetails(String imageUrl,String url) {
        String title = post_title.getText().toString();
        String details = post_details.getText().toString();
        String desc = details.substring(0, Math.min(details.length(), 250));
        String user = mAuth.getCurrentUser().getUid();
        Long time = System.currentTimeMillis();
        String datetime= null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date resultdate = new Date(time);
            datetime = (sdf.format(resultdate));
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<Comment> message=new ArrayList<>();
        ArrayList<String> like_id=new ArrayList<>();
        DocumentReference ref = FirebaseFirestore.getInstance().collection("forum_datas").document();
        String refid = ref.getId();

        Blog blogs  =   new Blog(user,url,datetime,title,details,filetype,mAuth.getCurrentUser().getDisplayName(),refid,url,message,like_id,ishoapproved,ishorejected);
        FirebaseFirestore.getInstance().collection("forum_datas").document(refid)
                .set(blogs)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        pdialog.dismiss();
                        post_title.setText("");
                        post_details.setText("");
                        post_image.setImageResource(R.color.swipeselector_color_indicator_inactive);
                        Toast.makeText(PostActivity.this, "Post uploaded successfully", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PostActivity.this,BlogActivity.class);
                        startActivity(intent);
                        finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void toast(String message){

        Toast.makeText(PostActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }
}
