package eu.toldi.infinityforlemmy.fragments;

import static eu.toldi.infinityforlemmy.activities.CommentActivity.RETURN_EXTRA_COMMENT_DATA_KEY;
import static eu.toldi.infinityforlemmy.activities.CommentActivity.WRITE_COMMENT_REQUEST_CODE;
import static eu.toldi.infinityforlemmy.videoautoplay.media.PlaybackInfo.INDEX_UNSET;
import static eu.toldi.infinityforlemmy.videoautoplay.media.PlaybackInfo.TIME_UNSET;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.view.menu.MenuItemImpl;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ConcatAdapter;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.transition.AutoTransition;
import androidx.transition.TransitionManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.evernote.android.state.State;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.livefront.bridge.Bridge;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executor;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;

import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.DeleteThing;
import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SavePost;
import eu.toldi.infinityforlemmy.SaveThing;
import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.activities.CommentActivity;
import eu.toldi.infinityforlemmy.activities.EditPostActivity;
import eu.toldi.infinityforlemmy.activities.PostFilterPreferenceActivity;
import eu.toldi.infinityforlemmy.activities.SubmitCrosspostActivity;
import eu.toldi.infinityforlemmy.activities.ViewPostDetailActivity;
import eu.toldi.infinityforlemmy.adapters.CommentsRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.adapters.PostDetailRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.apis.StreamableAPI;
import eu.toldi.infinityforlemmy.asynctasks.LoadUserData;
import eu.toldi.infinityforlemmy.bottomsheetfragments.PostCommentSortTypeBottomSheetFragment;
import eu.toldi.infinityforlemmy.comment.Comment;
import eu.toldi.infinityforlemmy.comment.FetchComment;
import eu.toldi.infinityforlemmy.comment.FetchRemovedComment;
import eu.toldi.infinityforlemmy.comment.FetchRemovedCommentReveddit;
import eu.toldi.infinityforlemmy.commentfilter.CommentFilter;
import eu.toldi.infinityforlemmy.commentfilter.FetchCommentFilter;
import eu.toldi.infinityforlemmy.community.BlockCommunity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.CustomToroContainer;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.dto.EditPostDTO;
import eu.toldi.infinityforlemmy.events.ChangeNSFWBlurEvent;
import eu.toldi.infinityforlemmy.events.ChangeNetworkStatusEvent;
import eu.toldi.infinityforlemmy.events.ChangeSpoilerBlurEvent;
import eu.toldi.infinityforlemmy.events.FlairSelectedEvent;
import eu.toldi.infinityforlemmy.events.PostUpdateEventToPostDetailFragment;
import eu.toldi.infinityforlemmy.events.PostUpdateEventToPostList;
import eu.toldi.infinityforlemmy.message.ReadMessage;
import eu.toldi.infinityforlemmy.post.FetchPost;
import eu.toldi.infinityforlemmy.post.FetchRemovedPost;
import eu.toldi.infinityforlemmy.post.HidePost;
import eu.toldi.infinityforlemmy.post.LemmyPostAPI;
import eu.toldi.infinityforlemmy.post.MarkPostAsRead;
import eu.toldi.infinityforlemmy.post.Post;
import eu.toldi.infinityforlemmy.post.enrich.PostEnricher;
import eu.toldi.infinityforlemmy.readpost.InsertReadPost;
import eu.toldi.infinityforlemmy.subreddit.FetchSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.user.BlockUser;
import eu.toldi.infinityforlemmy.user.FetchUserData;
import eu.toldi.infinityforlemmy.user.UserData;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import eu.toldi.infinityforlemmy.videoautoplay.ExoCreator;
import eu.toldi.infinityforlemmy.videoautoplay.media.PlaybackInfo;
import eu.toldi.infinityforlemmy.videoautoplay.media.VolumeInfo;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ViewPostDetailFragment extends Fragment implements FragmentCommunicator {

    public static final String EXTRA_POST_DATA = "EPD";
    public static final String EXTRA_POST_ID = "EPI";
    public static final String EXTRA_SINGLE_COMMENT_ID = "ESCI";

    public static final String EXTRA_SINGLE_COMMENT_PARENT_ID = "ESCPID";
    public static final String EXTRA_CONTEXT_NUMBER = "ECN";
    public static final String EXTRA_MESSAGE_FULLNAME = "EMF";
    public static final String EXTRA_POST_LIST_POSITION = "EPLP";
    private static final int EDIT_POST_REQUEST_CODE = 2;
    private static final String SCROLL_POSITION_STATE = "SPS";

    @BindView(R.id.swipe_refresh_layout_view_post_detail_fragment)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.post_detail_recycler_view_view_post_detail_fragment)
    CustomToroContainer mRecyclerView;
    RecyclerView mCommentsRecyclerView;
    @BindView(R.id.fetch_post_info_linear_layout_view_post_detail_fragment)
    LinearLayout mFetchPostInfoLinearLayout;
    @BindView(R.id.fetch_post_info_image_view_view_post_detail_fragment)
    ImageView mFetchPostInfoImageView;
    @BindView(R.id.fetch_post_info_text_view_view_post_detail_fragment)
    TextView mFetchPostInfoTextView;
    @Inject
    @Named("no_oauth")
    RetrofitHolder mRetrofit;
    @Inject
    @Named("pushshift")
    Retrofit pushshiftRetrofit;
    @Inject
    @Named("reveddit")
    Retrofit revedditRetrofit;
    @Inject
    @Named("gfycat")
    Retrofit mGfycatRetrofit;
    @Inject
    @Named("redgifs")
    Retrofit mRedgifsRetrofit;
    @Inject
    Provider<StreamableAPI> mStreamableApiProvider;
    @Inject
    RedditDataRoomDatabase mRedditDataRoomDatabase;
    @Inject
    @Named("default")
    SharedPreferences mSharedPreferences;
    @Inject
    @Named("sort_type")
    SharedPreferences mSortTypeSharedPreferences;
    @Inject
    @Named("nsfw_and_spoiler")
    SharedPreferences mNsfwAndSpoilerSharedPreferences;
    @Inject
    @Named("current_account")
    SharedPreferences mCurrentAccountSharedPreferences;
    @Inject
    @Named("post_details")
    SharedPreferences mPostDetailsSharedPreferences;
    @Inject
    @Named("post_history")
    SharedPreferences mPostHistorySharedPreferences;
    @Inject
    CustomThemeWrapper mCustomThemeWrapper;
    @Inject
    ExoCreator mExoCreator;
    @Inject
    Executor mExecutor;
    @Inject
    MarkPostAsRead markPostAsRead;
    @Inject
    LemmyPostAPI mLemmyPostAPI;
    @Inject
    PostEnricher postEnricher;
    @State
    Post mPost;
    @State
    boolean isLoadingMoreChildren = false;
    @State
    boolean isRefreshing = false;
    @State
    boolean isSingleCommentThreadMode = false;
    @State
    ArrayList<Comment> comments;
    @State
    ArrayList<Integer> children;

    @State
    int pages_loaded = 0;
    @State
    boolean loadMoreChildrenSuccess = true;
    @State
    boolean hasMoreChildren;
    @State
    boolean isFetchingComments = false;
    @State
    int mMessageFullname;
    @State
    SortType.Type sortType;
    @State
    boolean mRespectSubredditRecommendedSortType;
    @State
    long viewPostDetailFragmentId;
    @State
    boolean commentFilterFetched;
    @State
    CommentFilter mCommentFilter = new CommentFilter();

    @State
    boolean isCommunityBlocked;

    private ViewPostDetailActivity activity;
    private RequestManager mGlide;
    private Locale mLocale;
    private Menu mMenu;
    private String mAccessToken;
    private String mAccountName;
    private String mAccountQualifiedName;
    private int postListPosition = -1;
    private Integer mSingleCommentId;
    private Integer mSingleCommentParentId;
    private String mContextNumber;
    private boolean showToast = false;
    private boolean mIsSmoothScrolling = false;
    private boolean mLockFab;
    private boolean mSwipeUpToHideFab;
    private boolean mExpandChildren;
    private boolean mSeparatePostAndComments = false;
    private boolean mMarkPostsAsRead;
    private ConcatAdapter mConcatAdapter;
    private PostDetailRecyclerViewAdapter mPostAdapter;
    private CommentsRecyclerViewAdapter mCommentsAdapter;
    private RecyclerView.SmoothScroller mSmoothScroller;
    private Drawable mSavedIcon;
    private Drawable mUnsavedIcon;
    private ColorDrawable backgroundSwipeRight;
    private ColorDrawable backgroundSwipeLeft;
    private Drawable drawableSwipeRight;
    private Drawable drawableSwipeLeft;
    private int swipeLeftAction;
    private int swipeRightAction;
    private float swipeActionThreshold;
    private ItemTouchHelper touchHelper;
    private int scrollPosition;

    public ViewPostDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_view_post_detail, container, false);

        ((Infinity) activity.getApplication()).getAppComponent().inject(this);

        setHasOptionsMenu(true);

        Bridge.restoreInstanceState(this, savedInstanceState);

        ButterKnife.bind(this, rootView);

        EventBus.getDefault().register(this);

        applyTheme();



        mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
        mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
        mAccountQualifiedName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, null);

        mSavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_toolbar_24dp);
        mUnsavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_border_toolbar_24dp);

        if (getResources().getBoolean(R.bool.isTablet) || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mCommentsRecyclerView = rootView.findViewById(R.id.comments_recycler_view_view_post_detail_fragment);
        }
        if (!((mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_POST_AND_COMMENTS_IN_LANDSCAPE_MODE, true)
                && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
                || (mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_POST_AND_COMMENTS_IN_PORTRAIT_MODE, false)
                && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT))) {
            if (mCommentsRecyclerView != null) {
                mCommentsRecyclerView.setVisibility(View.GONE);
                mCommentsRecyclerView = null;
            }
        } else {
            mSeparatePostAndComments = true;
        }

        if (activity != null && activity.isImmersiveInterface()) {
            mRecyclerView.setPadding(0, 0, 0, activity.getNavBarHeight() + mRecyclerView.getPaddingBottom());
            if (mCommentsRecyclerView != null) {
                mCommentsRecyclerView.setPadding(0, 0, 0, activity.getNavBarHeight() + mCommentsRecyclerView.getPaddingBottom());
            }
            showToast = true;
        }

        mLockFab = mSharedPreferences.getBoolean(SharedPreferencesUtils.LOCK_JUMP_TO_NEXT_TOP_LEVEL_COMMENT_BUTTON, false);
        mSwipeUpToHideFab = mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_UP_TO_HIDE_JUMP_TO_NEXT_TOP_LEVEL_COMMENT_BUTTON, false);
        mExpandChildren = !mSharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_TOP_LEVEL_COMMENTS_FIRST, false);
        mMarkPostsAsRead = mPostHistorySharedPreferences.getBoolean(mAccountName + SharedPreferencesUtils.MARK_POSTS_AS_READ_BASE, false);
        if (savedInstanceState == null) {
            mRespectSubredditRecommendedSortType = mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false);
            viewPostDetailFragmentId = System.currentTimeMillis();
        } else {
            scrollPosition = savedInstanceState.getInt(SCROLL_POSITION_STATE);
            // if the scrollPosition < 0 do nothing
            if (scrollPosition >= 0) {
                if (getResources().getBoolean(R.bool.isTablet)) {
                    boolean separatePortrait = mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_POST_AND_COMMENTS_IN_PORTRAIT_MODE, true);
                    boolean separateLandscape = mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_POST_AND_COMMENTS_IN_LANDSCAPE_MODE, true);
                    if (separatePortrait != separateLandscape) {
                        if (mCommentsRecyclerView != null) {
                            //restore the position for commentsadapter
                            scrollPosition--;
                            mCommentsRecyclerView.scrollToPosition(scrollPosition);
                        } else {
                            // restore the position for mrecyclerview
                            scrollPosition++;
                            mRecyclerView.scrollToPosition(scrollPosition);
                        }
                    }
                } else {
                    if (mSeparatePostAndComments) {
                        if (mCommentsRecyclerView != null) {
                            scrollPosition--;
                            mCommentsRecyclerView.scrollToPosition(scrollPosition);
                        }
                    } else {
                        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                            if (mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_POST_AND_COMMENTS_IN_LANDSCAPE_MODE, true)) {
                                scrollPosition++;
                                mRecyclerView.scrollToPosition(scrollPosition);
                            }
                        }
                    }
                }
            }
        }

        mGlide = Glide.with(this);
        mLocale = getResources().getConfiguration().locale;

        if (children != null && children.size() > 0) {
            (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (!mIsSmoothScrolling && !mLockFab) {
                        if (!recyclerView.canScrollVertically(1)) {
                            activity.hideFab();
                        } else {
                            if (dy > 0) {
                                if (mSwipeUpToHideFab) {
                                    activity.showFab();
                                } else {
                                    activity.hideFab();
                                }
                            } else {
                                if (mSwipeUpToHideFab) {
                                    activity.hideFab();
                                } else {
                                    activity.showFab();
                                }
                            }
                        }
                    }

                    if (!isLoadingMoreChildren && loadMoreChildrenSuccess) {
                        int visibleItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getChildCount();
                        int totalItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getItemCount();
                        int firstVisibleItemPosition = ((LinearLayoutManagerBugFixed) (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager()).findFirstVisibleItemPosition();

                        if (mCommentsAdapter != null && mCommentsAdapter.getItemCount() >= 1 && (visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
                            fetchMoreComments();
                        }
                    }
                }

                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        mIsSmoothScrolling = false;
                    }
                }
            });
        } else {
            (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (!mIsSmoothScrolling && !mLockFab) {
                        if (!recyclerView.canScrollVertically(1)) {
                            activity.hideFab();
                        } else {
                            if (dy > 0) {
                                if (mSwipeUpToHideFab) {
                                    activity.showFab();
                                } else {
                                    activity.hideFab();
                                }
                            } else {
                                if (mSwipeUpToHideFab) {
                                    activity.hideFab();
                                } else {
                                    activity.showFab();
                                }
                            }
                        }
                    }
                }

                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        mIsSmoothScrolling = false;
                    }
                }
            });
        }

        boolean enableSwipeAction = mSharedPreferences.getBoolean(SharedPreferencesUtils.ENABLE_SWIPE_ACTION, false);
        boolean vibrateWhenActionTriggered = mSharedPreferences.getBoolean(SharedPreferencesUtils.VIBRATE_WHEN_ACTION_TRIGGERED, true);
        swipeActionThreshold = Float.parseFloat(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_ACTION_THRESHOLD, "0.3"));
        swipeRightAction = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_RIGHT_ACTION, "1"));
        swipeLeftAction = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_LEFT_ACTION, "0"));
        initializeSwipeActionDrawable();
        touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            boolean exceedThreshold = false;

            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                if (!(viewHolder instanceof CommentsRecyclerViewAdapter.CommentBaseViewHolder)) {
                    return makeMovementFlags(0, 0);
                }
                int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
                return makeMovementFlags(0, swipeFlags);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public boolean isItemViewSwipeEnabled() {
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                if (touchHelper != null) {
                    exceedThreshold = false;
                    touchHelper.attachToRecyclerView(null);
                    touchHelper.attachToRecyclerView((mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView));
                }
            }

            @Override
            public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

                if (isCurrentlyActive) {
                    View itemView = viewHolder.itemView;
                    int horizontalOffset = (int) Utils.convertDpToPixel(16, activity);
                    if (dX > 0) {
                        if (dX > (itemView.getRight() - itemView.getLeft()) * swipeActionThreshold) {
                            if (!exceedThreshold) {
                                exceedThreshold = true;
                                if (vibrateWhenActionTriggered) {
                                    viewHolder.itemView.setHapticFeedbackEnabled(true);
                                    viewHolder.itemView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
                                }
                            }
                            backgroundSwipeRight.setBounds(0, itemView.getTop(), itemView.getRight(), itemView.getBottom());
                        } else {
                            exceedThreshold = false;
                            backgroundSwipeRight.setBounds(0, 0, 0, 0);
                        }

                        drawableSwipeRight.setBounds(itemView.getLeft() + ((int) dX) - horizontalOffset - drawableSwipeRight.getIntrinsicWidth(),
                                (itemView.getBottom() + itemView.getTop() - drawableSwipeRight.getIntrinsicHeight()) / 2,
                                itemView.getLeft() + ((int) dX) - horizontalOffset,
                                (itemView.getBottom() + itemView.getTop() + drawableSwipeRight.getIntrinsicHeight()) / 2);
                        backgroundSwipeRight.draw(c);
                        drawableSwipeRight.draw(c);
                    } else if (dX < 0) {
                        if (-dX > (itemView.getRight() - itemView.getLeft()) * swipeActionThreshold) {
                            if (!exceedThreshold) {
                                exceedThreshold = true;
                                if (vibrateWhenActionTriggered) {
                                    viewHolder.itemView.setHapticFeedbackEnabled(true);
                                    viewHolder.itemView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
                                }
                            }
                            backgroundSwipeLeft.setBounds(0, itemView.getTop(), itemView.getRight(), itemView.getBottom());
                        } else {
                            exceedThreshold = false;
                            backgroundSwipeLeft.setBounds(0, 0, 0, 0);
                        }
                        drawableSwipeLeft.setBounds(itemView.getRight() + ((int) dX) + horizontalOffset,
                                (itemView.getBottom() + itemView.getTop() - drawableSwipeLeft.getIntrinsicHeight()) / 2,
                                itemView.getRight() + ((int) dX) + horizontalOffset + drawableSwipeLeft.getIntrinsicWidth(),
                                (itemView.getBottom() + itemView.getTop() + drawableSwipeLeft.getIntrinsicHeight()) / 2);
                        backgroundSwipeLeft.draw(c);
                        drawableSwipeLeft.draw(c);
                    }
                } else {
                    if (exceedThreshold) {
                        if (mCommentsAdapter != null) {
                            mCommentsAdapter.onItemSwipe(viewHolder, dX > 0 ? ItemTouchHelper.END : ItemTouchHelper.START, swipeLeftAction, swipeRightAction);
                        }
                        exceedThreshold = false;
                    }
                }
            }

            @Override
            public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
                return 100;
            }
        });

        if (enableSwipeAction) {
            touchHelper.attachToRecyclerView((mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView));
        }

        mSwipeRefreshLayout.setOnRefreshListener(() -> refresh());

        mSmoothScroller = new LinearSmoothScroller(activity) {
            @Override
            protected int getVerticalSnapPreference() {
                return LinearSmoothScroller.SNAP_TO_START;
            }
        };

        mSingleCommentId = getArguments().getInt(EXTRA_SINGLE_COMMENT_ID, 0);
        mSingleCommentParentId = getArguments().getInt(EXTRA_SINGLE_COMMENT_PARENT_ID, 0);
        mContextNumber = getArguments().getString(EXTRA_CONTEXT_NUMBER, "8");

        if (savedInstanceState == null) {
            if (mSingleCommentId != 0) {
                isSingleCommentThreadMode = true;
            }
            mMessageFullname = getArguments().getInt(EXTRA_MESSAGE_FULLNAME);

            if (!mRespectSubredditRecommendedSortType || isSingleCommentThreadMode) {
                sortType = loadSortType();
                activity.setTitle(sortType.fullName);
            }
        } else {
            if (sortType != null) {
                activity.setTitle(sortType.fullName);
            }
        }

        if (getArguments().containsKey(EXTRA_POST_LIST_POSITION)) {
            postListPosition = getArguments().getInt(EXTRA_POST_LIST_POSITION, -1);
        }

        bindView();

        return rootView;
    }

    private void bindView() {
        if (mAccessToken != null && mMessageFullname != 0) {
            ReadMessage.readMessage(mRetrofit.getRetrofit(), mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() {
                @Override
                public void readSuccess() {
                    mMessageFullname = 0;
                }

                @Override
                public void readFailed() {

                }
            });
        }

        if (mPost == null) {
            mPost = getArguments().getParcelable(EXTRA_POST_DATA);
        }

        if (mPost == null) {
            fetchPostAndCommentsById(getArguments().getInt(EXTRA_POST_ID));
        } else {
            setupMenu();

            mPostAdapter = new PostDetailRecyclerViewAdapter(activity,
                    this, mExecutor, mCustomThemeWrapper, mRetrofit, mGfycatRetrofit,
                    mRedgifsRetrofit, mStreamableApiProvider, mRedditDataRoomDatabase, mGlide,
                    mSeparatePostAndComments, mAccessToken, mAccountName, mPost, mLocale,
                    mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostDetailsSharedPreferences,
                    mExoCreator, post -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)));
            mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
                    this, mCustomThemeWrapper, mExecutor, mRetrofit,
                    mAccessToken, mAccountQualifiedName, mPost, mLocale, mSingleCommentId
                    , isSingleCommentThreadMode, mSharedPreferences, mCurrentAccountSharedPreferences,
                    new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
                        @Override
                        public void retryFetchingComments() {
                            fetchCommentsRespectRecommendedSort(false);
                        }

                        @Override
                        public void retryFetchingMoreComments() {
                            isLoadingMoreChildren = false;
                            loadMoreChildrenSuccess = true;

                            fetchMoreComments();
                        }

                        @Override
                        public SortType.Type getSortType() {
                            return sortType;
                        }
                    });
            if (mCommentsRecyclerView != null) {
                mRecyclerView.setAdapter(mPostAdapter);
                mCommentsRecyclerView.setAdapter(mCommentsAdapter);
            } else {
                mConcatAdapter = new ConcatAdapter(mPostAdapter, mCommentsAdapter);
                mRecyclerView.setAdapter(mConcatAdapter);
            }

            if (commentFilterFetched) {
                fetchCommentsAfterCommentFilterAvailable();
            } else {
                FetchCommentFilter.fetchCommentFilter(mExecutor, new Handler(Looper.getMainLooper()), mRedditDataRoomDatabase, mPost.getSubredditName(),
                        commentFilter -> {
                            mCommentFilter = commentFilter;
                            commentFilterFetched = true;
                            fetchCommentsAfterCommentFilterAvailable();
                        });
            }
        }

        mRecyclerView.setCacheManager(mPostAdapter);
        mRecyclerView.setPlayerInitializer(order -> {
            VolumeInfo volumeInfo = new VolumeInfo(true, 0f);
            return new PlaybackInfo(INDEX_UNSET, TIME_UNSET, volumeInfo);
        });
    }

    public void fetchCommentsAfterCommentFilterAvailable() {
        if (comments == null) {
            fetchCommentsRespectRecommendedSort(false);
        } else {
            if (isRefreshing) {
                isRefreshing = false;
                refresh(true, true);
            } else if (isFetchingComments) {
                fetchCommentsRespectRecommendedSort(false);
            } else {
                mCommentsAdapter.addComments(comments, hasMoreChildren);
                if (isLoadingMoreChildren) {
                    isLoadingMoreChildren = false;
                    fetchMoreComments();
                }
            }
        }
    }

    private void setupMenu() {
        if (mMenu != null) {
            MenuItem saveItem = mMenu.findItem(R.id.action_save_view_post_detail_fragment);
            MenuItem hideItem = mMenu.findItem(R.id.action_hide_view_post_detail_fragment);

            mMenu.findItem(R.id.action_comment_view_post_detail_fragment).setVisible(true);
            mMenu.findItem(R.id.action_sort_view_post_detail_fragment).setVisible(true);

            if (mAccessToken != null) {
                if (mPost.isSaved()) {
                    saveItem.setVisible(true);
                    saveItem.setIcon(mSavedIcon);
                } else {
                    saveItem.setVisible(true);
                    saveItem.setIcon(mUnsavedIcon);
                }

                if (mPost.isHidden()) {
                    hideItem.setVisible(true);
                    Utils.setTitleWithCustomFontToMenuItem(activity.typeface, hideItem, activity.getString(R.string.action_unhide_post));
                } else {
                    hideItem.setVisible(true);
                    Utils.setTitleWithCustomFontToMenuItem(activity.typeface, hideItem, activity.getString(R.string.action_hide_post));
                }
            } else {
                saveItem.setVisible(false);
                hideItem.setVisible(false);
            }

            if (mPost.getAuthorNamePrefixed().equals(mAccountQualifiedName)) {
                mMenu.findItem(R.id.action_edit_view_post_detail_fragment).setVisible(true);
                mMenu.findItem(R.id.action_delete_view_post_detail_fragment).setVisible(true);

                MenuItem nsfwItem = mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment);
                nsfwItem.setVisible(true);
                if (mPost.isNSFW()) {
                    Utils.setTitleWithCustomFontToMenuItem(activity.typeface, nsfwItem, activity.getString(R.string.action_unmark_nsfw));
                } else {
                    Utils.setTitleWithCustomFontToMenuItem(activity.typeface, nsfwItem, activity.getString(R.string.action_mark_nsfw));
                }

                MenuItem spoilerItem = mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment);
                spoilerItem.setVisible(true);

                mMenu.findItem(R.id.action_block_user_view_post_detail_fragment).setVisible(false);
            }

            mMenu.findItem(R.id.action_view_crosspost_parent_view_post_detail_fragment).setVisible(mPost.getCrosspostParentId() != null);

            if ("[deleted]".equals(mPost.getAuthor()) ||
                    "[deleted]".equals(mPost.getSelfText()) ||
                    "[removed]".equals(mPost.getSelfText())
            ) {
                mMenu.findItem(R.id.action_see_removed_view_post_detail_fragment).setVisible(true);
            }
        }
    }

    private void initializeSwipeActionDrawable() {
        if (swipeRightAction == SharedPreferencesUtils.SWIPE_ACITON_DOWNVOTE) {
            backgroundSwipeRight = new ColorDrawable(mCustomThemeWrapper.getDownvoted());
            drawableSwipeRight = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_downward_black_24dp, null);
        } else {
            backgroundSwipeRight = new ColorDrawable(mCustomThemeWrapper.getUpvoted());
            drawableSwipeRight = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_upward_black_24dp, null);
        }

        if (swipeLeftAction == SharedPreferencesUtils.SWIPE_ACITON_UPVOTE) {
            backgroundSwipeLeft = new ColorDrawable(mCustomThemeWrapper.getUpvoted());
            drawableSwipeLeft = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_upward_black_24dp, null);
        } else {
            backgroundSwipeLeft = new ColorDrawable(mCustomThemeWrapper.getDownvoted());
            drawableSwipeLeft = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_downward_black_24dp, null);
        }
    }

    private Drawable getMenuItemIcon(int drawableId) {
        Drawable icon = AppCompatResources.getDrawable(activity, drawableId);
        if (icon != null) {
            icon.setTint(mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor());
        }

        return icon;
    }

    public void addComment(Comment comment) {
        if (mCommentsAdapter != null) {
            mCommentsAdapter.addComment(comment);
        }
        if (mPostAdapter != null) {
            mPostAdapter.addOneComment();
        }
        EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
    }

    public void addChildComment(Comment comment, int parentFullname, int parentPosition) {
        if (mCommentsAdapter != null) {
            mCommentsAdapter.addChildComment(comment, parentFullname, parentPosition);
        }
        if (mPostAdapter != null) {
            mPostAdapter.addOneComment();
        }
        EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
    }

    public void editComment(String commentAuthor, String commentContentMarkdown, int position) {
        if (mCommentsAdapter != null) {
            mCommentsAdapter.editComment(commentAuthor,
                    commentContentMarkdown,
                    position);
        }
    }

    public void changeFlair(Flair flair) {

    }

    public void changeSortType(SortType sortType) {
        mFetchPostInfoLinearLayout.setVisibility(View.GONE);
        mGlide.clear(mFetchPostInfoImageView);
        if (children != null) {
            children.clear();
            pages_loaded = 0;
            mCommentsAdapter.clearLoadedComments();
        }
        this.sortType = sortType.getType();
        if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SAVE_SORT_TYPE, true)) {
            mSortTypeSharedPreferences.edit().putString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, sortType.getType().name()).apply();
        }
        mRespectSubredditRecommendedSortType = false;
        fetchCommentsRespectRecommendedSort(false, sortType.getType());
    }

    @NonNull
    private SortType.Type loadSortType() {
        String sortTypeName = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.NEW.name());
        return SortType.Type.valueOf(sortTypeName);
    }

    public void goToTop() {
        ((LinearLayoutManagerBugFixed) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(0, 0);
        if (mCommentsRecyclerView != null) {
            ((LinearLayoutManagerBugFixed) mCommentsRecyclerView.getLayoutManager()).scrollToPositionWithOffset(0, 0);
        }
    }

    public void saveComment(int position, boolean isSaved) {
        if (mCommentsAdapter != null) {
            mCommentsAdapter.setSaveComment(position, isSaved);
        }
    }

    public void searchComment(String query, boolean searchNextComment) {
        if (mCommentsAdapter != null) {
            ArrayList<Comment> visibleComments = mCommentsAdapter.getVisibleComments();
            int currentSearchIndex = mCommentsAdapter.getSearchCommentIndex();
            if (currentSearchIndex >= 0) {
                mCommentsAdapter.notifyItemChanged(currentSearchIndex);
            }
            if (visibleComments != null) {
                if (searchNextComment) {
                    for (int i = currentSearchIndex + 1; i < visibleComments.size(); i++) {
                        if (visibleComments.get(i).getCommentRawText() != null &&
                                visibleComments.get(i).getCommentRawText().toLowerCase().contains(query.toLowerCase())) {
                            if (mCommentsAdapter != null) {
                                mCommentsAdapter.highlightSearchResult(i);
                                mCommentsAdapter.notifyItemChanged(i);
                                if (mCommentsRecyclerView == null) {
                                    mRecyclerView.scrollToPosition(i + 1);
                                } else {
                                    mCommentsRecyclerView.scrollToPosition(i);
                                }
                            }
                            return;
                        }
                    }

                } else {
                    for (int i = currentSearchIndex - 1; i >= 0; i--) {
                        if (visibleComments.get(i).getCommentRawText() != null &&
                                visibleComments.get(i).getCommentRawText().toLowerCase().contains(query.toLowerCase())) {
                            if (mCommentsAdapter != null) {
                                mCommentsAdapter.highlightSearchResult(i);
                                mCommentsAdapter.notifyItemChanged(i);
                                if (mCommentsRecyclerView == null) {
                                    mRecyclerView.scrollToPosition(i + 1);
                                } else {
                                    mCommentsRecyclerView.scrollToPosition(i);
                                }
                            }
                            return;
                        }
                    }

                }
                return;
            }
        }
    }

    public void resetSearchCommentIndex() {
        if (mCommentsAdapter != null) {
            mCommentsAdapter.resetCommentSearchIndex();
        }
    }

    public void loadIcon(String authorName, LoadIconListener loadIconListener) {
        if (activity.authorIcons.containsKey(authorName)) {
            loadIconListener.loadIconSuccess(authorName, activity.authorIcons.get(authorName));
        } else {
            LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, authorName,
                    mRetrofit.getRetrofit(), iconImageUrl -> {
                        activity.authorIcons.put(authorName, iconImageUrl);
                        loadIconListener.loadIconSuccess(authorName, iconImageUrl);
                    });
        }
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.view_post_detail_fragment, menu);
        applyMenuItemTheme(menu);
        mMenu = menu;
        if (mPost != null) {
            setupMenu();
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.action_search_view_post_detail_fragment) {
            if (activity.toggleSearchPanelVisibility() && mCommentsAdapter != null) {
                mCommentsAdapter.resetCommentSearchIndex();
            }
        } else if (itemId == R.id.action_refresh_view_post_detail_fragment) {
            refresh(true, true);
            return true;
        } else if (itemId == R.id.action_comment_view_post_detail_fragment) {
            if (mPost != null) {
                if (mPost.isArchived()) {
                    showMessage(R.string.archived_post_reply_unavailable);
                    return true;
                }

                if (mPost.isLocked()) {
                    showMessage(R.string.locked_post_comment_unavailable);
                    return true;
                }

                if (mAccessToken == null) {
                    showMessage(R.string.login_first);
                    return true;
                }

                Intent intent = new Intent(activity, CommentActivity.class);
                intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_TITLE_KEY, mPost.getTitle());
                intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_BODY_MARKDOWN_KEY, mPost.getSelfText());
                intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_BODY_KEY, mPost.getSelfTextPlain());
                intent.putExtra(CommentActivity.EXTRA_POST_ID_KEY, mPost.getId());
                intent.putExtra(CommentActivity.EXTRA_PARENT_DEPTH_KEY, 0);
                intent.putExtra(CommentActivity.EXTRA_IS_REPLYING_KEY, false);
                startActivityForResult(intent, WRITE_COMMENT_REQUEST_CODE);
            }
            return true;
        } else if (itemId == R.id.action_save_view_post_detail_fragment) {
            if (mPost != null && mAccessToken != null) {
                SavePost savePost = new SavePost();
                if (mPost.isSaved()) {
                    item.setIcon(mUnsavedIcon);
                    savePost.unsaveThing(mRetrofit.getRetrofit(), mAccessToken, mPost.getId(),
                            new SaveThing.SaveThingListener() {
                                @Override
                                public void success() {
                                    if (isAdded()) {
                                        mPost.setSaved(false);
                                        item.setIcon(mUnsavedIcon);
                                        showMessage(R.string.post_unsaved_success);
                                    }
                                    EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                                }

                                @Override
                                public void failed() {
                                    if (isAdded()) {
                                        mPost.setSaved(true);
                                        item.setIcon(mSavedIcon);
                                        showMessage(R.string.post_unsaved_failed);
                                    }
                                    EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                                }
                            });
                } else {
                    item.setIcon(mSavedIcon);
                    savePost.saveThing(mRetrofit.getRetrofit(), mAccessToken, mPost.getId(),
                            new SaveThing.SaveThingListener() {
                                @Override
                                public void success() {
                                    if (isAdded()) {
                                        mPost.setSaved(true);
                                        item.setIcon(mSavedIcon);
                                        showMessage(R.string.post_saved_success);
                                    }
                                    EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                                }

                                @Override
                                public void failed() {
                                    if (isAdded()) {
                                        mPost.setSaved(false);
                                        item.setIcon(mUnsavedIcon);
                                        showMessage(R.string.post_saved_failed);
                                    }
                                    EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                                }
                            });
                }
            }
            return true;
        } else if (itemId == R.id.action_sort_view_post_detail_fragment) {
            if (mPost != null) {
                PostCommentSortTypeBottomSheetFragment postCommentSortTypeBottomSheetFragment = PostCommentSortTypeBottomSheetFragment.getNewInstance(sortType);
                postCommentSortTypeBottomSheetFragment.show(activity.getSupportFragmentManager(), postCommentSortTypeBottomSheetFragment.getTag());
            }
            return true;
        } else if (itemId == R.id.action_view_crosspost_parent_view_post_detail_fragment) {
            Intent crosspostIntent = new Intent(activity, ViewPostDetailActivity.class);
            crosspostIntent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, mPost.getCrosspostParentId());
            startActivity(crosspostIntent);
            return true;
        } else if (itemId == R.id.action_hide_view_post_detail_fragment) {
            if (mPost != null && mAccessToken != null) {
                if (mPost.isHidden()) {
                    Utils.setTitleWithCustomFontToMenuItem(activity.typeface, item, getString(R.string.action_hide_post));

                    HidePost.unhidePost(mRetrofit.getRetrofit(), mAccessToken, mPost.getFullName(), new HidePost.HidePostListener() {
                        @Override
                        public void success() {
                            mPost.setHidden(false);
                            Utils.setTitleWithCustomFontToMenuItem(activity.typeface, item, activity.getString(R.string.action_hide_post));
                            showMessage(R.string.post_unhide_success);
                            EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                        }

                        @Override
                        public void failed() {
                            mPost.setHidden(true);
                            Utils.setTitleWithCustomFontToMenuItem(activity.typeface, item, activity.getString(R.string.action_unhide_post));
                            showMessage(R.string.post_unhide_failed);
                            EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                        }
                    });
                } else {
                    Utils.setTitleWithCustomFontToMenuItem(activity.typeface, item, getString(R.string.action_unhide_post));

                    HidePost.hidePost(mRetrofit.getRetrofit(), mAccessToken, mPost.getFullName(), new HidePost.HidePostListener() {
                        @Override
                        public void success() {
                            mPost.setHidden(true);
                            Utils.setTitleWithCustomFontToMenuItem(activity.typeface, item, activity.getString(R.string.action_unhide_post));
                            showMessage(R.string.post_hide_success);
                            EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                        }

                        @Override
                        public void failed() {
                            mPost.setHidden(false);
                            Utils.setTitleWithCustomFontToMenuItem(activity.typeface, item, activity.getString(R.string.action_hide_post));
                            showMessage(R.string.post_hide_failed);
                            EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                        }
                    });
                }
            }
            return true;
        } else if (itemId == R.id.action_edit_view_post_detail_fragment) {
            Intent editPostIntent = new Intent(activity, EditPostActivity.class);
            editPostIntent.putExtra(EditPostActivity.EXTRA_DATA, mPost);
            startActivityForResult(editPostIntent, EDIT_POST_REQUEST_CODE);
            return true;
        } else if (itemId == R.id.action_delete_view_post_detail_fragment) {
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.delete_this_post)
                    .setMessage(R.string.are_you_sure)
                    .setPositiveButton(R.string.delete, (dialogInterface, i)
                            -> DeleteThing.deletePost(mRetrofit.getRetrofit(), mPost.getId(), mAccessToken, new DeleteThing.DeleteThingListener() {
                        @Override
                        public void deleteSuccess() {
                            Toast.makeText(activity, R.string.delete_post_success, Toast.LENGTH_SHORT).show();
                            activity.finish();
                        }

                        @Override
                        public void deleteFailed() {
                            showMessage(R.string.delete_post_failed);
                        }
                    }))
                    .setNegativeButton(R.string.cancel, null)
                    .show();
            return true;
        } else if (itemId == R.id.action_nsfw_view_post_detail_fragment) {
            if (mPost.isNSFW()) {
                unmarkNSFW();
            } else {
                markNSFW();
            }
            return true;
        } else if (itemId == R.id.action_spoiler_view_post_detail_fragment) {
            return true;
        } else if (itemId == R.id.action_block_user_view_post_detail_fragment) {
            if (mAccessToken == null) {
                Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
                return true;
            }
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.block_user)
                    .setMessage(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> FetchUserData.fetchUserData(mRetrofit.getRetrofit(), mPost.getAuthorNamePrefixed(), new FetchUserData.FetchUserDataListener() {

                        @Override
                        public void onFetchUserDataSuccess(UserData userData, int inboxCount) {
                            BlockUser.blockUser(mRetrofit.getRetrofit(), mAccessToken, userData.getId(), true, new BlockUser.BlockUserListener() {

                                @Override
                                public void success() {
                                    Toast.makeText(activity, R.string.block_user_success, Toast.LENGTH_SHORT).show();
                                    activity.finish();
                                }

                                @Override
                                public void failed() {
                                    Toast.makeText(activity, R.string.block_user_failed, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFetchUserDataFailed() {
                            Toast.makeText(activity, R.string.block_user_failed, Toast.LENGTH_SHORT).show();
                        }
                    }))
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        } else if (itemId == R.id.action_block_community_view_post_detail_fragment) {
            if (mAccessToken == null) {
                Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
                return true;
            }
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.block_community)
                    .setMessage(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> FetchSubredditData.fetchSubredditData(mRetrofit.getRetrofit(), mPost.getSubredditNamePrefixed(), mAccessToken, new FetchSubredditData.FetchSubredditDataListener() {
                        @Override
                        public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
                            BlockCommunity.INSTANCE.blockCommunity(mRetrofit.getRetrofit(), subredditData.getId(), mAccessToken, new BlockCommunity.BlockCommunityListener() {
                                @Override
                                public void onBlockCommunitySuccess() {
                                    Toast.makeText(activity, R.string.block_community_success, Toast.LENGTH_SHORT).show();
                                    activity.finish();
                                }

                                @Override
                                public void onBlockCommunityError() {
                                    Toast.makeText(activity, R.string.block_community_failed, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFetchSubredditDataFail(boolean isQuarantined) {
                            Toast.makeText(activity, R.string.block_community_failed, Toast.LENGTH_SHORT).show();
                        }
                    }))
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        } else if (itemId == R.id.action_report_view_post_detail_fragment) {
            if (mAccessToken == null) {
                Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
                return true;
            }
            LayoutInflater inflater = LayoutInflater.from(activity);
            View view = inflater.inflate(R.layout.dialog_report, null);
            EditText reasonEditText = view.findViewById(R.id.reasonEditText);
            reasonEditText.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
            reasonEditText.setHintTextColor(mCustomThemeWrapper.getSecondaryTextColor());
            if (activity.typeface != null) {
                reasonEditText.setTypeface(activity.typeface);
            }
            MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(activity)
                    .setTitle(R.string.report_post)
                    .setView(view)
                    .setNegativeButton(R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss())
                    .setPositiveButton(R.string.send_report, (dialogInterface, i) -> {
                        String reason = reasonEditText.getText().toString();
                        if (reason.isEmpty()) {
                            Toast.makeText(activity, "A report reason must be provided", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        mLemmyPostAPI.reportPost(mPost.getId(), reason, mAccessToken, new LemmyPostAPI.ReportPostCallback() {
                            @Override
                            public void onSuccess() {
                                Toast.makeText(activity, R.string.report_successful, Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFailure() {
                                Toast.makeText(activity, R.string.report_failed, Toast.LENGTH_SHORT).show();
                            }
                        });
                    });
            AlertDialog dialog = builder.create();
            dialog.show();

            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            positiveButton.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
            negativeButton.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
            return true;
        } else if (itemId == R.id.action_see_removed_view_post_detail_fragment) {
            showRemovedPost();
            return true;
        } else if (itemId == R.id.action_crosspost_view_post_detail_fragment) {
            Intent submitCrosspostIntent = new Intent(activity, SubmitCrosspostActivity.class);
            submitCrosspostIntent.putExtra(SubmitCrosspostActivity.EXTRA_POST, mPost);
            startActivity(submitCrosspostIntent);
            return true;
        } else if (itemId == R.id.action_add_to_post_filter_view_post_detail_fragment) {
            Intent intent = new Intent(activity, PostFilterPreferenceActivity.class);
            intent.putExtra(PostFilterPreferenceActivity.EXTRA_POST, mPost);
            startActivity(intent);
            return true;
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == WRITE_COMMENT_REQUEST_CODE) {
            if (data != null && resultCode == Activity.RESULT_OK) {
                if (data.hasExtra(RETURN_EXTRA_COMMENT_DATA_KEY)) {
                    Comment comment = data.getParcelableExtra(RETURN_EXTRA_COMMENT_DATA_KEY);
                    if (comment != null && comment.getDepth() == 0) {
                        addComment(comment);
                    } else {
                        int parentFullname = data.getIntExtra(CommentActivity.EXTRA_POST_ID_KEY,0);
                        int parentPosition = data.getIntExtra(CommentActivity.EXTRA_PARENT_POSITION_KEY, -1);
                        if (parentFullname > 0) {
                            addChildComment(comment, parentFullname, parentPosition);
                        }
                    }
                } else {
                    Toast.makeText(activity, R.string.send_comment_failed, Toast.LENGTH_SHORT).show();
                }
            }
        } else if (requestCode == EDIT_POST_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                refresh(true, false);
            }
        }
    }

    private void tryMarkingPostAsRead() {
        if (mMarkPostsAsRead && mPost != null && !mPost.isRead()) {
            mPost.markAsRead();
            markPostAsRead.markPostAsRead(mPost.getId(), mAccessToken, new MarkPostAsRead.MarkPostAsReadListener() {
                @Override
                public void onMarkPostAsReadSuccess() {
                    InsertReadPost.insertReadPost(mRedditDataRoomDatabase, mExecutor, mAccountQualifiedName, mPost.getId());
                    EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                }

                @Override
                public void onMarkPostAsReadFailed() {
                    Toast.makeText(activity, R.string.mark_post_as_read_failed, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mPostAdapter != null) {
            mPostAdapter.setCanStartActivity(true);
        }
        if (mRecyclerView != null) {
            mRecyclerView.onWindowVisibilityChanged(View.VISIBLE);
        }
        tryMarkingPostAsRead();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mRecyclerView != null) {
            mRecyclerView.onWindowVisibilityChanged(View.GONE);
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        comments = mCommentsAdapter == null ? null : mCommentsAdapter.getVisibleComments();
        if (mCommentsRecyclerView != null) {
            LinearLayoutManager myLayoutManager = (LinearLayoutManager) mCommentsRecyclerView.getLayoutManager();
            scrollPosition = myLayoutManager != null ? myLayoutManager.findFirstVisibleItemPosition() : 0;

        } else {
            LinearLayoutManager myLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            scrollPosition = myLayoutManager != null ? myLayoutManager.findFirstVisibleItemPosition() : 0;
        }
        outState.putInt(SCROLL_POSITION_STATE, scrollPosition);
        Bridge.saveInstanceState(this, outState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Bridge.clear(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (mRecyclerView != null) {
            mRecyclerView.addOnWindowFocusChangedListener(null);
        }
        super.onDestroy();
    }

    @SuppressLint("RestrictedApi")
    protected boolean applyMenuItemTheme(Menu menu) {
        if (mCustomThemeWrapper != null) {
            for (int i = 0; i < menu.size(); i++) {
                MenuItem item = menu.getItem(i);
                if (((MenuItemImpl) item).requestsActionButton()) {
                    MenuItemCompat.setIconTintList(item, ColorStateList
                            .valueOf(mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor()));
                }
                Utils.setTitleWithCustomFontToMenuItem(activity.typeface, item, null);
            }
        }
        return true;
    }

    private void fetchPostAndCommentsById(int subredditId) {
        mFetchPostInfoLinearLayout.setVisibility(View.GONE);
        mSwipeRefreshLayout.setRefreshing(true);
        mGlide.clear(mFetchPostInfoImageView);
        FetchPost.fetchPost(mExecutor, new Handler(), mRetrofit.getRetrofit(), String.valueOf(subredditId), mAccessToken,
                postEnricher, new FetchPost.FetchPostListener() {
                    @Override
                    public void fetchPostSuccess(Post post) {
                        if (!isAdded()) {
                            return;
                        }
                        mPost = post;
                        mPostAdapter = new PostDetailRecyclerViewAdapter(activity,
                                ViewPostDetailFragment.this, mExecutor, mCustomThemeWrapper,
                                mRetrofit, mGfycatRetrofit, mRedgifsRetrofit,
                                mStreamableApiProvider, mRedditDataRoomDatabase, mGlide, mSeparatePostAndComments,
                                mAccessToken, mAccountName, mPost, mLocale, mSharedPreferences,
                                mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences,
                                mPostDetailsSharedPreferences, mExoCreator,
                                post1 -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)));
                        mSwipeRefreshLayout.setRefreshing(false);
                        FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken, post.getId(), mSingleCommentId == null || mSingleCommentId == 0 ? null : mSingleCommentParentId == 0 ? mSingleCommentId : mSingleCommentParentId, sortType, mExpandChildren, 1, mCommentFilter, new FetchComment.FetchCommentListener() {
                            @Override
                            public void onFetchCommentSuccess(ArrayList<Comment> expandedComments, Integer parentId, ArrayList<Integer> children) {
                                pages_loaded++;
                                mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
                                        ViewPostDetailFragment.this, mCustomThemeWrapper, mExecutor,
                                        mRetrofit, mAccessToken, mAccountQualifiedName, mPost, mLocale,
                                        mSingleCommentId, isSingleCommentThreadMode, mSharedPreferences, mCurrentAccountSharedPreferences,
                                        new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
                                            @Override
                                            public void retryFetchingComments() {
                                                fetchCommentsRespectRecommendedSort(false);
                                            }

                                            @Override
                                            public void retryFetchingMoreComments() {
                                                isLoadingMoreChildren = false;
                                                loadMoreChildrenSuccess = true;

                                                fetchMoreComments();
                                            }

                                            @Override
                                            public SortType.Type getSortType() {
                                                return sortType;
                                            }
                                        });
                                if (mCommentsRecyclerView != null) {
                                    mRecyclerView.setAdapter(mPostAdapter);
                                    mCommentsRecyclerView.setAdapter(mCommentsAdapter);
                                } else {
                                    mConcatAdapter = new ConcatAdapter(mPostAdapter, mCommentsAdapter);
                                    mRecyclerView.setAdapter(mConcatAdapter);
                                }

                                if (mRespectSubredditRecommendedSortType) {
                                    fetchCommentsRespectRecommendedSort(false);
                                }
                                ViewPostDetailFragment.this.children = children;
                            }


                            @Override
                            public void onFetchCommentFailed() {
                                if (isAdded()) {
                                    showErrorView(subredditId);
                                }
                            }
                        });
                    }

                    @Override
                    public void fetchPostFailed() {
                        if (isAdded()) {
                            showMessage(R.string.refresh_post_failed);
                            isRefreshing = false;
                        }
                    }
                });

    }

    private void fetchCommentsRespectRecommendedSort(boolean changeRefreshState, SortType.Type sortType) {
        if (mRespectSubredditRecommendedSortType && mPost != null) {
            if (mPost.getSuggestedSort() != null && !mPost.getSuggestedSort().equals("null") && !mPost.getSuggestedSort().equals("")) {
                try {
                    SortType.Type sortTypeType = SortType.Type.valueOf(mPost.getSuggestedSort().toUpperCase(Locale.US));
                    activity.setTitle(sortTypeType.fullName);
                    ViewPostDetailFragment.this.sortType = sortTypeType;
                    fetchComments(changeRefreshState, ViewPostDetailFragment.this.sortType);
                    return;
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
            FetchSubredditData.fetchSubredditData(mRetrofit.getRetrofit(), mPost.getSubredditNamePrefixed(), mAccessToken,
                    new FetchSubredditData.FetchSubredditDataListener() {
                        @Override
                        public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
                            String suggestedCommentSort = "top";
                            SortType.Type sortTypeType;
                            try {
                                sortTypeType = SortType.Type.fromValue(suggestedCommentSort);
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                                sortTypeType = loadSortType();
                            }
                            activity.setTitle(sortTypeType.fullName);
                            ViewPostDetailFragment.this.sortType = sortTypeType;
                            fetchComments(changeRefreshState, ViewPostDetailFragment.this.sortType);
                        }

                        @Override
                        public void onFetchSubredditDataFail(boolean isQuarantined) {
                            mRespectSubredditRecommendedSortType = false;
                            SortType.Type sortTypeType = loadSortType();
                            activity.setTitle(sortTypeType.fullName);
                            ViewPostDetailFragment.this.sortType = sortTypeType;
                        }
                    });
        } else {
            fetchComments(changeRefreshState, sortType);
        }
    }

    private void fetchComments(boolean changeRefreshState, SortType.Type sortType) {
        isFetchingComments = true;
        mCommentsAdapter.setSingleComment(mSingleCommentId, isSingleCommentThreadMode);
        mCommentsAdapter.initiallyLoading();
        Integer commentId = null;
        if (isSingleCommentThreadMode) {
            commentId = mSingleCommentId;
        }


        FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken, mPost.getId(), mSingleCommentId == null || mSingleCommentId == 0 ? null : mSingleCommentParentId == 0 ? mSingleCommentId : mSingleCommentParentId, sortType, mExpandChildren, pages_loaded + 1,
                mCommentFilter, new FetchComment.FetchCommentListener() {
                    @Override
                    public void onFetchCommentSuccess(ArrayList<Comment> expandedComments,
                                                      Integer parentId, ArrayList<Integer> children) {
                        isFetchingComments = false;
                        ViewPostDetailFragment.this.children = children;
                        pages_loaded++;
                        comments = expandedComments;
                        hasMoreChildren = expandedComments.size() != 0;
                        mCommentsAdapter.addComments(expandedComments, hasMoreChildren);
                        if (hasMoreChildren) {
                            fetchMoreComments();
                        }

/*
                        if (children.size() > 0) {
                            (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).clearOnScrollListeners();
                            (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).addOnScrollListener(new RecyclerView.OnScrollListener() {
                                @Override
                                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                                    super.onScrolled(recyclerView, dx, dy);
                                    if (!mIsSmoothScrolling && !mLockFab) {
                                        if (!recyclerView.canScrollVertically(1)) {
                                            activity.hideFab();
                                        } else {
                                            if (dy > 0) {
                                                if (mSwipeUpToHideFab) {
                                                    activity.showFab();
                                                } else {
                                                    activity.hideFab();
                                                }
                                            } else {
                                                if (mSwipeUpToHideFab) {
                                                    activity.hideFab();
                                                } else {
                                                    activity.showFab();
                                                }
                                            }
                                        }
                                    }

                                    if (!isLoadingMoreChildren && loadMoreChildrenSuccess) {
                                        int visibleItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getChildCount();
                                        int totalItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getItemCount();
                                        int firstVisibleItemPosition = ((LinearLayoutManagerBugFixed) (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager()).findFirstVisibleItemPosition();

                                        if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
                                            fetchMoreComments();
                                        }
                                    }
                                }

                                @Override
                                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                                        mIsSmoothScrolling = false;
                                    }
                                }
                            });
                        }*/
                        if (changeRefreshState) {
                            isRefreshing = false;
                        }
                    }

                    @Override
                    public void onFetchCommentFailed() {
                        isFetchingComments = false;
                        if(pages_loaded == 0)
                            mCommentsAdapter.initiallyLoadCommentsFailed();
                        if (changeRefreshState) {
                            isRefreshing = false;
                        }
                    }
                });
    }

    private void fetchCommentsRespectRecommendedSort(boolean changeRefreshState) {
        fetchCommentsRespectRecommendedSort(changeRefreshState, sortType);
    }

    void fetchMoreComments() {
        if (isFetchingComments || isLoadingMoreChildren || !loadMoreChildrenSuccess) {
            return;
        }

        isLoadingMoreChildren = true;

        FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken,
                mPost.getId(), (mSingleCommentId == null || mSingleCommentId == 0) ? null : (mSingleCommentParentId == null || mSingleCommentParentId == 0 ? mSingleCommentId : mSingleCommentParentId), sortType, mExpandChildren, pages_loaded + 1, mCommentFilter, new FetchComment.FetchCommentListener() {
                    @Override
                    public void onFetchCommentSuccess(ArrayList<Comment> expandedComments, Integer parentId, ArrayList<Integer> children) {
                        pages_loaded++;
                        hasMoreChildren = !children.isEmpty();
                        mCommentsAdapter.addComments(expandedComments, hasMoreChildren);
                        isLoadingMoreChildren = false;
                        loadMoreChildrenSuccess = true;
                    }

                    @Override
                    public void onFetchCommentFailed() {
                        isLoadingMoreChildren = false;
                        loadMoreChildrenSuccess = false;
                        mCommentsAdapter.loadMoreCommentsFailed();
                    }
                });
    }

    public void refresh(boolean fetchPost, boolean fetchComments) {
        if (mPostAdapter != null && !isRefreshing) {
            isRefreshing = true;

            mFetchPostInfoLinearLayout.setVisibility(View.GONE);
            mGlide.clear(mFetchPostInfoImageView);

            if (!fetchPost && fetchComments) {
                fetchCommentsRespectRecommendedSort(true);
            }

            if (fetchPost) {
                Retrofit retrofit = mRetrofit.getRetrofit();

                FetchPost.fetchPost(mExecutor, new Handler(), retrofit, String.valueOf(mPost.getId()), mAccessToken,
                        postEnricher, new FetchPost.FetchPostListener() {
                            @Override
                            public void fetchPostSuccess(Post post) {
                                if (isAdded()) {
                                    mPost = post;
                                    mPostAdapter.updatePost(mPost);
                                    EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
                                    setupMenu();
                                    mSwipeRefreshLayout.setRefreshing(false);

                                    if (fetchComments) {
                                        pages_loaded = 0;
                                        mCommentsAdapter.clearLoadedComments();
                                        fetchCommentsRespectRecommendedSort(true);
                                    } else {
                                        isRefreshing = false;
                                    }
                                }
                            }

                            @Override
                            public void fetchPostFailed() {
                                if (isAdded()) {
                                    showMessage(R.string.refresh_post_failed);
                                    isRefreshing = false;
                                }
                            }
                        });
            }
        }
    }

    private void showErrorView(int subredditId) {
        mSwipeRefreshLayout.setRefreshing(false);
        mFetchPostInfoLinearLayout.setVisibility(View.VISIBLE);
        mFetchPostInfoLinearLayout.setOnClickListener(view -> fetchPostAndCommentsById(subredditId));
        mFetchPostInfoTextView.setText(R.string.load_post_error);
        mGlide.load(R.drawable.error_image).into(mFetchPostInfoImageView);
    }

    private void showMessage(int resId) {
        if (showToast) {
            Toast.makeText(activity, resId, Toast.LENGTH_SHORT).show();
        } else {
            activity.showSnackBar(resId);
        }
    }

    private void markNSFW() {
        if (mMenu != null) {
            mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw);
        }

        Map<String, String> params = new HashMap<>();
        params.put(APIUtils.ID_KEY, mPost.getFullName());
        mRetrofit.getRetrofit().create(LemmyAPI.class).postUpdate(new EditPostDTO(mPost.getId(), mPost.getTitle(), mPost.getUrl(), mPost.getSelfText(), true, null, mAccessToken))
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                        if (response.isSuccessful()) {
                            if (mMenu != null) {
                                mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw);
                            }

                            refresh(true, false);
                            showMessage(R.string.mark_nsfw_success);
                        } else {
                            if (mMenu != null) {
                                mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw);
                            }

                            showMessage(R.string.mark_nsfw_failed);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                        if (mMenu != null) {
                            mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw);
                        }

                        showMessage(R.string.mark_nsfw_failed);
                    }
                });
    }

    private void unmarkNSFW() {
        if (mMenu != null) {
            mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw);
        }

        Map<String, String> params = new HashMap<>();
        params.put(APIUtils.ID_KEY, mPost.getFullName());
        mRetrofit.getRetrofit().create(LemmyAPI.class).postUpdate(new EditPostDTO(mPost.getId(), mPost.getTitle(), mPost.getUrl(), mPost.getSelfText(), false, null, mAccessToken))
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                        if (response.isSuccessful()) {
                            if (mMenu != null) {
                                mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw);
                            }

                            refresh(true, false);
                            showMessage(R.string.unmark_nsfw_success);
                        } else {
                            if (mMenu != null) {
                                mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw);
                            }

                            showMessage(R.string.unmark_nsfw_failed);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                        if (mMenu != null) {
                            mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw);
                        }

                        showMessage(R.string.unmark_nsfw_failed);
                    }
                });
    }

    public void deleteComment(int commentId, int position) {
        new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                .setTitle(R.string.delete_this_comment)
                .setMessage(R.string.are_you_sure)
                .setPositiveButton(R.string.delete, (dialogInterface, i)
                        -> DeleteThing.deleteComment(mRetrofit.getRetrofit(), commentId, mAccessToken, new DeleteThing.DeleteThingListener() {
                    @Override
                    public void deleteSuccess() {
                        Toast.makeText(activity, R.string.delete_post_success, Toast.LENGTH_SHORT).show();
                        mCommentsAdapter.deleteComment(position);
                    }

                    @Override
                    public void deleteFailed() {
                        Toast.makeText(activity, R.string.delete_post_failed, Toast.LENGTH_SHORT).show();
                    }
                }))
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    public void showRemovedComment(Comment comment, int position) {
        Toast.makeText(activity, R.string.fetching_removed_comment, Toast.LENGTH_SHORT).show();
        FetchRemovedComment.fetchRemovedComment(
                mExecutor, new Handler(), pushshiftRetrofit, comment,
                new FetchRemovedComment.FetchRemovedCommentListener() {
                    @Override
                    public void fetchSuccess(Comment fetchedComment, Comment originalComment) {
                        mCommentsAdapter.editComment(fetchedComment, originalComment, position);
                    }

                    @Override
                    public void fetchFailed() {
                        // Reveddit fallback
                        FetchRemovedCommentReveddit.fetchRemovedComment(mExecutor, new Handler(), revedditRetrofit,
                                comment, mPost.getPostTimeMillis(), mPost.getNComments(),
                                new FetchRemovedCommentReveddit.FetchRemovedCommentListener() {
                                    @Override
                                    public void fetchSuccess(Comment fetchedComment, Comment originalComment) {
                                        mCommentsAdapter.editComment(fetchedComment, originalComment, position);
                                    }

                                    @Override
                                    public void fetchFailed() {
                                        Toast.makeText(activity, R.string.show_removed_comment_failed, Toast.LENGTH_SHORT).show();
                                    }
                                });
                    }
                });
    }

    public void changeToNormalThreadMode() {
        isSingleCommentThreadMode = false;
        mSingleCommentId = null;
        mSingleCommentParentId = null;
        mRespectSubredditRecommendedSortType = mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false);
        refresh(false, true);
    }

    public void scrollToNextParentComment() {
        RecyclerView chooseYourView = mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView;
        if (mCommentsAdapter != null && chooseYourView != null) {
            int currentPosition = ((LinearLayoutManagerBugFixed) chooseYourView.getLayoutManager()).findFirstVisibleItemPosition();
            //int nextParentPosition = mCommentsAdapter.getNextParentCommentPosition(mCommentsRecyclerView == null ? currentPosition - 1 : currentPosition);
            int nextParentPosition = mCommentsAdapter.getNextParentCommentPosition(mCommentsRecyclerView == null && !isSingleCommentThreadMode ? currentPosition - 1 : currentPosition);
            if (nextParentPosition < 0) {
                return;
            }
            mSmoothScroller.setTargetPosition(mCommentsRecyclerView == null && !isSingleCommentThreadMode ? nextParentPosition + 1 : nextParentPosition);
            mIsSmoothScrolling = true;
            chooseYourView.getLayoutManager().startSmoothScroll(mSmoothScroller);
        }
    }

    public void scrollToPreviousParentComment() {
        RecyclerView chooseYourView = mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView;
        if (mCommentsAdapter != null && chooseYourView != null) {
            int currentPosition = ((LinearLayoutManagerBugFixed) chooseYourView.getLayoutManager()).findFirstVisibleItemPosition();
            //int previousParentPosition = mCommentsAdapter.getPreviousParentCommentPosition(mCommentsRecyclerView == null ? currentPosition - 1 : currentPosition);
            int previousParentPosition = mCommentsAdapter.getPreviousParentCommentPosition(mCommentsRecyclerView == null && !isSingleCommentThreadMode ? currentPosition - 1 : currentPosition);
            if (previousParentPosition < 0) {
                return;
            }
            mSmoothScroller.setTargetPosition(mCommentsRecyclerView == null && !isSingleCommentThreadMode ? previousParentPosition + 1 : previousParentPosition);
            mIsSmoothScrolling = true;
            chooseYourView.getLayoutManager().startSmoothScroll(mSmoothScroller);
        }
    }

    public void delayTransition() {
        TransitionManager.beginDelayedTransition((mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView), new AutoTransition());
    }

    public void showRemovedPost() {
        Toast.makeText(activity, R.string.fetching_removed_post, Toast.LENGTH_SHORT).show();
        FetchRemovedPost.fetchRemovedPost(
                pushshiftRetrofit,
                mPost,
                new FetchRemovedPost.FetchRemovedPostListener() {
                    @Override
                    public void fetchSuccess(Post post) {
                        mPost = post;
                        tryMarkingPostAsRead();
                        if (mPostAdapter != null) {
                            mPostAdapter.updatePost(post);
                        }
                    }

                    @Override
                    public void fetchFailed() {
                        Toast.makeText(activity, R.string.show_removed_post_failed, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public boolean getIsNsfwSubreddit() {
        if (activity != null) {
            return activity.isNsfwSubreddit();
        }
        return false;
    }

    @Subscribe
    public void onPostUpdateEvent(PostUpdateEventToPostDetailFragment event) {
        if (mPost.getId() == event.post.getId()) {
            mPost.setVoteType(event.post.getVoteType());
            mPost.setSaved(event.post.isSaved());
            if (mMenu != null) {
                if (event.post.isSaved()) {
                    mMenu.findItem(R.id.action_save_view_post_detail_fragment).setIcon(mSavedIcon);
                } else {
                    mMenu.findItem(R.id.action_save_view_post_detail_fragment).setIcon(mUnsavedIcon);
                }
            }
            if (mPostAdapter != null) {
                mPostAdapter.updatePost(mPost);
            }
        }
    }

    @Subscribe
    public void onChangeNSFWBlurEvent(ChangeNSFWBlurEvent event) {
        if (mPostAdapter != null) {
            mPostAdapter.setBlurNsfwAndDoNotBlurNsfwInNsfwSubreddits(event.needBlurNSFW, event.doNotBlurNsfwInNsfwSubreddits);
        }
        if (mCommentsRecyclerView != null) {
            refreshAdapter(mRecyclerView, mConcatAdapter);
        } else {
            refreshAdapter(mRecyclerView, mPostAdapter);
        }
    }

    @Subscribe
    public void onChangeSpoilerBlurEvent(ChangeSpoilerBlurEvent event) {
        if (mPostAdapter != null) {
            mPostAdapter.setBlurSpoiler(event.needBlurSpoiler);
        }
        if (mCommentsRecyclerView != null) {
            refreshAdapter(mRecyclerView, mConcatAdapter);
        } else {
            refreshAdapter(mRecyclerView, mPostAdapter);
        }
    }

    private void refreshAdapter(RecyclerView recyclerView, RecyclerView.Adapter<RecyclerView.ViewHolder> adapter) {
        int previousPosition = -1;
        if (recyclerView.getLayoutManager() != null) {
            previousPosition = ((LinearLayoutManagerBugFixed) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
        }

        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        recyclerView.setAdapter(null);
        recyclerView.setLayoutManager(null);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(layoutManager);

        if (previousPosition > 0) {
            recyclerView.scrollToPosition(previousPosition);
        }
    }

    @Subscribe
    public void onChangeNetworkStatusEvent(ChangeNetworkStatusEvent changeNetworkStatusEvent) {
        if (mPostAdapter != null) {
            String autoplay = mSharedPreferences.getString(SharedPreferencesUtils.VIDEO_AUTOPLAY, SharedPreferencesUtils.VIDEO_AUTOPLAY_VALUE_NEVER);
            String dataSavingMode = mSharedPreferences.getString(SharedPreferencesUtils.DATA_SAVING_MODE, SharedPreferencesUtils.DATA_SAVING_MODE_OFF);
            boolean stateChanged = false;
            if (autoplay.equals(SharedPreferencesUtils.VIDEO_AUTOPLAY_VALUE_ON_WIFI)) {
                mPostAdapter.setAutoplay(changeNetworkStatusEvent.connectedNetwork == Utils.NETWORK_TYPE_WIFI);
                stateChanged = true;
            }
            if (dataSavingMode.equals(SharedPreferencesUtils.DATA_SAVING_MODE_ONLY_ON_CELLULAR_DATA)) {
                mPostAdapter.setDataSavingMode(changeNetworkStatusEvent.connectedNetwork == Utils.NETWORK_TYPE_CELLULAR);
                stateChanged = true;
            }

            if (stateChanged) {
                if (mCommentsRecyclerView == null) {
                    refreshAdapter(mRecyclerView, mConcatAdapter);
                } else {
                    refreshAdapter(mRecyclerView, mPostAdapter);
                    refreshAdapter(mCommentsRecyclerView, mCommentsAdapter);
                }
            }
        }
    }

    @Subscribe
    public void onFlairSelectedEvent(FlairSelectedEvent event) {
        if (event.viewPostDetailFragmentId == viewPostDetailFragmentId) {
            changeFlair(event.flair);
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (ViewPostDetailActivity) context;
    }

    @Override
    public void applyTheme() {
        mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
        mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
        mFetchPostInfoTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
        if (activity.typeface != null) {
            mFetchPostInfoTextView.setTypeface(activity.contentTypeface);
        }
    }

    private void onWindowFocusChanged(boolean hasWindowsFocus) {
        if (mPostAdapter != null) {
            mPostAdapter.setCanPlayVideo(hasWindowsFocus);
        }
    }

    public interface LoadIconListener {
        void loadIconSuccess(String authorName, String iconUrl);
    }
}
