package com.ttiglobal.inttilectgpchat.blog.Helper;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.blog.BlogDetails;
import com.ttiglobal.inttilectgpchat.blog.VideoView;

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

import de.hdodenhof.circleimageview.CircleImageView;

public class BlogViewHolder extends RecyclerView.ViewHolder {

    View view;
    FirebaseAuth mAuth;
    String user_id;
    ArrayList<HashMap<String, String>> childHashMap = new ArrayList<>();
    TextView txt_click_like;
    DocumentSnapshot document;
    DocumentReference ref;
    Map<String, Object> map;
    private LinearLayout llout_like_div,llout_comment_div;

    public BlogViewHolder(View itemView) {
        super(itemView);
        view = itemView;
        mAuth = FirebaseAuth.getInstance();
        user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
        llout_comment_div = view.findViewById(R.id.comment_div);
        llout_like_div=view.findViewById(R.id.like_div);
    }

    public void setImage(String url, Context ctx) {
        final ImageView post_image = view.findViewById(R.id.post_image);
        Glide.with(ctx)
                .applyDefaultRequestOptions(new RequestOptions()
                        .placeholder(R.drawable.image_not_available)
                        .error(R.drawable.image_not_available)
                        .diskCacheStrategy(DiskCacheStrategy.ALL))
                .load(url)
                .into(post_image);

    }

    public void setUser(final String user_name, final String file_url, Context applicationContext) {
        final TextView username = view.findViewById(R.id.user_name);
        final CircleImageView userimage = view.findViewById(R.id.profile_image);
        username.setText(user_name);
        userimage.setImageResource(R.drawable.user1);
//        Glide.with(applicationContext)
//                .applyDefaultRequestOptions(new RequestOptions()
//                        .placeholder(R.drawable.user1)
//                        .error(R.drawable.user1)
//                        .diskCacheStrategy(DiskCacheStrategy.ALL))
//                .load(file_url)
//                .into(userimage);
    }

    public void setTitle(String title) {
        TextView head = view.findViewById(R.id.post_title);
        head.setText(title);
    }

    public void setVisibilty() {
        view.setVisibility(View.GONE);
    }

    public void setDesc(String desc) {
        TextView post_desc = view.findViewById(R.id.post_desc);
        post_desc.setText(desc);
    }

    public void setLikes(final Activity activity, final String ref_id, final String userId) {
        final Animation animation = AnimationUtils.loadAnimation(activity.getApplicationContext(), R.anim.zoom_in);
        final Animation animation2 = AnimationUtils.loadAnimation(activity.getApplicationContext(), R.anim.zoom_out);

        final TextView like_count = view.findViewById(R.id.like_coun);

        txt_click_like = view.findViewById(R.id.Likes1);
        final ImageView img_click_like = view.findViewById(R.id.like_btn1);


        populateLike(ref_id, like_count, img_click_like);

        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //img_click_like.startAnimation(animation2);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        llout_like_div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final MediaPlayer sound = MediaPlayer.create(activity.getApplicationContext(), R.raw.like_btn_click);
                sound.start();


                if (childHashMap != null) {
                    if (childHashMap.contains(user_id)) {
                        DocumentReference msgpost = FirebaseFirestore.getInstance().collection("forum_datas").document(ref_id);
                        msgpost.update("like_id", FieldValue.arrayRemove(user_id));
                    } else {
                        DocumentReference msgpost = FirebaseFirestore.getInstance().collection("forum_datas").document(ref_id);
                        msgpost.update("like_id", FieldValue.arrayUnion(user_id));
                    }


                }

//                DocumentReference msgpost = FirebaseFirestore.getInstance().collection("blog_datas").document(ref_id);
//                msgpost.update("like_id", FieldValue.arrayUnion(user_id));


                populateLike(ref_id, like_count, img_click_like);
            }
        });
    }

    private void populateLike(String ref_id, final TextView txt_click, final ImageView img_click_like) {

        ref = FirebaseFirestore.getInstance().collection("forum_datas").document(ref_id);
        ref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    document = task.getResult();
                    assert document != null;
                    if (document.exists()) {
                        map = document.getData();
                        assert map != null;
                        childHashMap = (ArrayList<HashMap<String, String>>) map.get("like_id");

                        if (childHashMap != null) {
                            if (childHashMap.contains(user_id)) {
                                img_click_like.setImageResource(R.drawable.liked);
                                txt_click_like.setText("Liked");
                            } else {
                                img_click_like.setImageResource(R.drawable.unliked);
                                txt_click_like.setText("Like");
                            }

                            if (childHashMap.size() == 0)
                                txt_click.setText("0 Like");
                            else if (childHashMap.size() == 1)
                                txt_click.setText(childHashMap.size() + " Like");
                            else
                                txt_click.setText(childHashMap.size() + " Likes");
                        } else {
                            txt_click.setText("0 Like");
                        }
                    }

                }
            }

        });
    }

    public void showPostDetails(String is_ho_approved,String is_ho_rejected, final String sender_name, final String refId, final String imgurl, final String user, final String filetype, String time, final String title, final String details, final int size, final Activity activity) {

        final TextView post_title = view.findViewById(R.id.post_title);
        TextView post_desc = view.findViewById(R.id.post_desc);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (filetype != null && filetype.equalsIgnoreCase("1")) {
                    final Intent blogIntent = new Intent(activity, BlogDetails.class);
                    blogIntent.putExtra("file_url", imgurl);
                    blogIntent.putExtra("file_type", filetype);
                    blogIntent.putExtra("user_id", user);
                    blogIntent.putExtra("blog_title", title);
                    blogIntent.putExtra("blog_desc", details);
                    blogIntent.putExtra("ref_id", refId);
                    blogIntent.putExtra("sender_name",sender_name);
                    blogIntent.putExtra("comment_count", String.valueOf(size));
                    blogIntent.putExtra("likes", String.valueOf(childHashMap.size()));
                    activity.startActivity(blogIntent);
                } else {
                    final Intent videoIntent = new Intent(activity, VideoView.class);
                    videoIntent.putExtra("filepath", imgurl);
                    activity.startActivity(videoIntent);

                }
            }
        });

        post_desc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                post_title.performClick();
            }
        });
    }

    public void setCommentCount(int size) {
        TextView comment_count = view.findViewById(R.id.comment_coun);
        if (size == 1)
            comment_count.setText(size + " Comment");
        else if (size == 0)
            comment_count.setText("No Comments");
        else
            comment_count.setText(size + " Comments");
    }
}