package ml.docilealligator.infinityforreddit.activities;

import static ml.docilealligator.infinityforreddit.activities.CommentActivity.RETURN_EXTRA_COMMENT_DATA_KEY;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.Insets;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewGroupCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.inputmethod.EditorInfoCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.evernote.android.state.State;
import com.github.piasy.biv.BigImageViewer;
import com.github.piasy.biv.loader.glide.GlideImageLoader;
import com.google.android.material.snackbar.Snackbar;
import com.livefront.bridge.Bridge;

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

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

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

import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.account.Account;
import ml.docilealligator.infinityforreddit.asynctasks.AccountManagement;
import ml.docilealligator.infinityforreddit.comment.Comment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.databinding.ActivityViewPostDetailBinding;
import ml.docilealligator.infinityforreddit.events.NeedForPostListFromPostFragmentEvent;
import ml.docilealligator.infinityforreddit.events.ProvidePostListToViewPostDetailActivityEvent;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.fragments.MorePostsInfoFragment;
import ml.docilealligator.infinityforreddit.fragments.ViewPostDetailFragmentNew;
import ml.docilealligator.infinityforreddit.post.LoadingMorePostsStatus;
import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.post.PostType;
import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.readpost.ReadPostType;
import ml.docilealligator.infinityforreddit.readpost.ReadPostsListInterface;
import ml.docilealligator.infinityforreddit.thing.SortType;
import ml.docilealligator.infinityforreddit.thing.SortTypeSelectionCallback;
import ml.docilealligator.infinityforreddit.user.UserProfileImagesBatchLoader;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import ml.docilealligator.infinityforreddit.viewmodels.ViewPostDetailActivityViewModel;
import retrofit2.Retrofit;

public class ViewPostDetailActivity extends BaseActivity implements SortTypeSelectionCallback, ActivityToolbarInterface {

    public static final String EXTRA_POST_DATA = "EPD";
    public static final String EXTRA_POST_ID = "EPI";
    public static final String EXTRA_POST_LIST_POSITION = "EPLP";
    public static final String EXTRA_SINGLE_COMMENT_ID = "ESCI";
    public static final String EXTRA_CONTEXT_NUMBER = "ECN";
    public static final String EXTRA_MESSAGE_FULLNAME = "ENI";
    public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN";
    public static final String EXTRA_POST_FRAGMENT_ID = "EPFI";
    public static final String EXTRA_IS_NSFW_SUBREDDIT = "EINS";
    public static final int EDIT_COMMENT_REQUEST_CODE = 3;
    @State
    String mNewAccountName;
    @Inject
    @Named("no_oauth")
    Retrofit mRetrofit;
    @Inject
    @Named("oauth")
    Retrofit mOauthRetrofit;
    @Inject
    RedditDataRoomDatabase mRedditDataRoomDatabase;
    @Inject
    @Named("default")
    SharedPreferences mSharedPreferences;
    @Inject
    @Named("current_account")
    SharedPreferences mCurrentAccountSharedPreferences;
    @Inject
    @Named("post_details")
    SharedPreferences mPostDetailsSharedPreferences;
    @Inject
    CustomThemeWrapper mCustomThemeWrapper;
    @Inject
    Executor mExecutor;
    @Inject
    UserProfileImagesBatchLoader mLoader;
    @State
    ArrayList<Post> posts;
    @PostType
    @State
    int postType;
    @State
    String subredditName;
    @State
    String concatenatedSubredditNames;
    @State
    String username;
    @State
    String userWhere;
    @State
    String multiPath;
    @State
    String query;
    @State
    String trendingSource;
    @ReadPostType
    @State
    int readPostType;
    @State
    PostFilter postFilter;
    @State
    SortType.Type sortType;
    @State
    SortType.Time sortTime;
    @State
    Post post;
    @State
    @LoadingMorePostsStatus
    int mLoadingMorePostsStatus = LoadingMorePostsStatus.NOT_LOADING;
    public ViewPostDetailActivityViewModel viewPostDetailActivityViewModel;
    private FragmentManager mFragmentManager;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private long mPostFragmentId;
    private int mPostListPosition;
    private boolean mVolumeKeysNavigateComments;
    private boolean mIsNsfwSubreddit;
    private boolean mHideFab;
    private ActivityViewPostDetailBinding binding;
    @Nullable
    private ReadPostsListInterface readPostsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ((Infinity) getApplication()).getAppComponent().inject(this);

        super.onCreate(savedInstanceState);

        BigImageViewer.initialize(GlideImageLoader.with(this.getApplicationContext()));

        binding = ActivityViewPostDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Bridge.restoreInstanceState(this, savedInstanceState);

        EventBus.getDefault().register(this);

        applyCustomTheme();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();

            if (isChangeStatusBarIconColor()) {
                addOnOffsetChangedListener(binding.appbarLayoutViewPostDetailActivity);
            }

            if (isImmersiveInterfaceRespectForcedEdgeToEdge()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    window.setDecorFitsSystemWindows(false);
                } else {
                    window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                }
                ViewGroupCompat.installCompatInsetsDispatch(binding.getRoot());
                ViewCompat.setOnApplyWindowInsetsListener(binding.getRoot(), new OnApplyWindowInsetsListener() {
                    @NonNull
                    @Override
                    public WindowInsetsCompat onApplyWindowInsets(@NonNull View v, @NonNull WindowInsetsCompat insets) {
                        Insets allInsets = Utils.getInsets(insets, false, isForcedImmersiveInterface());

                        setMargins(binding.toolbarViewPostDetailActivity,
                                allInsets.left,
                                allInsets.top,
                                allInsets.right,
                                BaseActivity.IGNORE_MARGIN);

                        binding.viewPager2ViewPostDetailActivity.setPadding(allInsets.left, 0, allInsets.right, 0);

                        binding.searchPanelMaterialCardViewViewPostDetailActivity.setContentPadding(0, 0, 0, allInsets.bottom);

                        setMargins(binding.fabViewPostDetailActivity,
                                BaseActivity.IGNORE_MARGIN,
                                BaseActivity.IGNORE_MARGIN,
                                (int) Utils.convertDpToPixel(16, ViewPostDetailActivity.this) + allInsets.right,
                                (int) Utils.convertDpToPixel(16, ViewPostDetailActivity.this) + allInsets.bottom);

                        return insets;
                    }
                });
                /*adjustToolbar(binding.toolbarViewPostDetailActivity);

                int navBarHeight = getNavBarHeight();
                if (navBarHeight > 0) {
                    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) binding.fabViewPostDetailActivity.getLayoutParams();
                    params.bottomMargin += navBarHeight;
                    binding.fabViewPostDetailActivity.setLayoutParams(params);

                    binding.searchPanelMaterialCardViewViewPostDetailActivity.setContentPadding(binding.searchPanelMaterialCardViewViewPostDetailActivity.getPaddingStart(),
                            binding.searchPanelMaterialCardViewViewPostDetailActivity.getPaddingTop(),
                            binding.searchPanelMaterialCardViewViewPostDetailActivity.getPaddingEnd(),
                            binding.searchPanelMaterialCardViewViewPostDetailActivity.getPaddingBottom() + navBarHeight);
                }*/
            }
        }

        boolean swipeBetweenPosts = mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_BETWEEN_POSTS, false);
        if (!swipeBetweenPosts) {
            attachSliderPanelIfApplicable();
            binding.viewPager2ViewPostDetailActivity.setUserInputEnabled(false);
        } else {
            mViewPager2 = binding.viewPager2ViewPostDetailActivity;
        }

        mPostFragmentId = getIntent().getLongExtra(EXTRA_POST_FRAGMENT_ID, -1);

        mPostListPosition = getIntent().getIntExtra(EXTRA_POST_LIST_POSITION, -1);
        mIsNsfwSubreddit = getIntent().getBooleanExtra(EXTRA_IS_NSFW_SUBREDDIT, false);
        mHideFab = mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_FAB_IN_POST_DETAILS, false);
        if (mHideFab) {
            binding.fabViewPostDetailActivity.setVisibility(View.GONE);
        }

        mFragmentManager = getSupportFragmentManager();

        binding.toolbarViewPostDetailActivity.setTitle("");
        setSupportActionBar(binding.toolbarViewPostDetailActivity);
        setToolbarGoToTop(binding.toolbarViewPostDetailActivity);

        mVolumeKeysNavigateComments = mSharedPreferences.getBoolean(SharedPreferencesUtils.VOLUME_KEYS_NAVIGATE_COMMENTS, false);

        binding.fabViewPostDetailActivity.setOnClickListener(view -> {
            scrollToNextParentComment();
        });

        binding.fabViewPostDetailActivity.setOnLongClickListener(view -> scrollToPreviousParentComment());

        if (accountName.equals(Account.ANONYMOUS_ACCOUNT) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            binding.searchTextInputEditTextViewPostDetailActivity.setImeOptions(binding.searchTextInputEditTextViewPostDetailActivity.getImeOptions() | EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING);
        }

        binding.fabViewPostDetailActivity.bindRequiredData(
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ? getDisplay() : null,
                mPostDetailsSharedPreferences,
                getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
        );

        binding.fabViewPostDetailActivity.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                binding.fabViewPostDetailActivity.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                binding.fabViewPostDetailActivity.setCoordinates();
            }
        });

        viewPostDetailActivityViewModel = new ViewModelProvider(
                this,
                ViewPostDetailActivityViewModel.Companion.provideFactory(
                        mRetrofit, mOauthRetrofit, mRedditDataRoomDatabase, accessToken, mLoader
                )
        ).get(ViewPostDetailActivityViewModel.class);

        if (savedInstanceState == null) {
            viewPostDetailActivityViewModel.setPost(getIntent().getParcelableExtra(EXTRA_POST_DATA));
            mNewAccountName = getIntent().getStringExtra(EXTRA_NEW_ACCOUNT_NAME);
        } else {
            if (viewPostDetailActivityViewModel.getPost() == null) {
                viewPostDetailActivityViewModel.setPost(this.post);
            }
            if (viewPostDetailActivityViewModel.getPosts() == null) {
                viewPostDetailActivityViewModel.setPosts(this.posts);
            }
        }

        mSectionsPagerAdapter = new SectionsPagerAdapter(this);
        binding.viewPager2ViewPostDetailActivity.setAdapter(mSectionsPagerAdapter);

        if (swipeBetweenPosts && viewPostDetailActivityViewModel.getPosts() == null && mPostFragmentId > 0) {
            EventBus.getDefault().post(new NeedForPostListFromPostFragmentEvent(mPostFragmentId));
        }

        viewPostDetailActivityViewModel.getLoadMorePostsState().observe(this, new Observer<ViewPostDetailActivityViewModel.LoadMorePostsState>() {
            @Override
            public void onChanged(ViewPostDetailActivityViewModel.LoadMorePostsState loadMorePostsState) {
                mLoadingMorePostsStatus = loadMorePostsState.getStatus();
                MorePostsInfoFragment fragment =
                        mSectionsPagerAdapter.getMorePostsInfoFragment();
                if (fragment != null) {
                    fragment.setStatus(loadMorePostsState.getStatus());
                }
                if (loadMorePostsState.getStatus() == LoadingMorePostsStatus.LOADED) {
                    if (loadMorePostsState.getChangePage()) {
                        binding.viewPager2ViewPostDetailActivity.setCurrentItem(
                                viewPostDetailActivityViewModel.getPosts().size() - 1,
                                false
                        );
                    }
                    mSectionsPagerAdapter.notifyItemRangeInserted(
                            viewPostDetailActivityViewModel.getPosts().size(),
                            loadMorePostsState.getNNewPosts()
                    );
                }
            }
        });

        checkNewAccountAndBindView(savedInstanceState);
    }

    public void setTitle(String title) {
        binding.toolbarViewPostDetailActivity.setTitle(title);
    }

    public void showFab() {
        if (!mHideFab) {
            binding.fabViewPostDetailActivity.show();
        }
    }

    public void hideFab() {
        if (!mHideFab) {
            binding.fabViewPostDetailActivity.hide();
        }
    }

    public void showSnackBar(int resId) {
        Snackbar.make(binding.getRoot(), resId, Snackbar.LENGTH_SHORT).show();
    }

    public void scrollToNextParentComment() {
        if (mSectionsPagerAdapter != null) {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.scrollToNextParentComment();
            }
        }
    }

    public boolean scrollToPreviousParentComment() {
        if (mSectionsPagerAdapter != null) {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.scrollToPreviousParentComment();
                return true;
            }
        }

        return false;
    }

    public void scrollToParentComment(int position, int currentDepth) {
        if (mSectionsPagerAdapter != null) {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.scrollToParentComment(position, currentDepth);
            }
        }
    }

    @Override
    public SharedPreferences getDefaultSharedPreferences() {
        return mSharedPreferences;
    }

    @Override
    public SharedPreferences getCurrentAccountSharedPreferences() {
        return mCurrentAccountSharedPreferences;
    }

    @Override
    public CustomThemeWrapper getCustomThemeWrapper() {
        return mCustomThemeWrapper;
    }

    @Override
    protected void applyCustomTheme() {
        binding.getRoot().setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
        applyAppBarLayoutAndCollapsingToolbarLayoutAndToolbarTheme(binding.appbarLayoutViewPostDetailActivity,
                binding.collapsingToolbarLayoutViewPostDetailActivity, binding.toolbarViewPostDetailActivity);
        applyAppBarScrollFlagsIfApplicable(binding.collapsingToolbarLayoutViewPostDetailActivity);
        applyFABTheme(binding.fabViewPostDetailActivity);
        binding.searchPanelMaterialCardViewViewPostDetailActivity.setBackgroundTintList(ColorStateList.valueOf(mCustomThemeWrapper.getColorPrimary()));
        int searchPanelTextAndIconColor = mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor();
        binding.searchTextInputLayoutViewPostDetailActivity.setBoxStrokeColor(searchPanelTextAndIconColor);
        binding.searchTextInputLayoutViewPostDetailActivity.setDefaultHintTextColor(ColorStateList.valueOf(searchPanelTextAndIconColor));
        binding.searchTextInputEditTextViewPostDetailActivity.setTextColor(searchPanelTextAndIconColor);
        binding.previousResultImageViewViewPostDetailActivity.setColorFilter(searchPanelTextAndIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
        binding.nextResultImageViewViewPostDetailActivity.setColorFilter(searchPanelTextAndIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
        binding.closeSearchPanelImageViewViewPostDetailActivity.setColorFilter(searchPanelTextAndIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
        if (typeface != null) {
            binding.searchTextInputLayoutViewPostDetailActivity.setTypeface(typeface);
            binding.searchTextInputEditTextViewPostDetailActivity.setTypeface(typeface);
        }
    }

    private void checkNewAccountAndBindView(Bundle savedInstanceState) {
        if (mNewAccountName != null) {
            if (accountName.equals(Account.ANONYMOUS_ACCOUNT) || !accountName.equals(mNewAccountName)) {
                AccountManagement.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences,
                        mExecutor, new Handler(), mNewAccountName, newAccount -> {
                            EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
                            Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();

                            mNewAccountName = null;
                            if (newAccount != null) {
                                accessToken = newAccount.getAccessToken();
                                accountName = newAccount.getAccountName();
                            }

                            bindView(savedInstanceState);
                        });
            } else {
                bindView(savedInstanceState);
            }
        } else {
            bindView(savedInstanceState);
        }
    }

    private void bindView(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            binding.viewPager2ViewPostDetailActivity.setCurrentItem(getIntent().getIntExtra(EXTRA_POST_LIST_POSITION, 0), false);
        }
        binding.viewPager2ViewPostDetailActivity.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                List<Post> posts = viewPostDetailActivityViewModel.getPosts();
                if (posts != null && position > posts.size() - 5) {
                    viewPostDetailActivityViewModel.fetchMorePosts(
                            accessToken, accountName, false, postType,
                            subredditName, concatenatedSubredditNames, username,
                            userWhere, multiPath, query, sortType, sortTime, postFilter,
                            readPostType, readPostsList
                    );
                }
            }
        });

        binding.searchPanelMaterialCardViewViewPostDetailActivity.setOnClickListener(null);
        
        binding.nextResultImageViewViewPostDetailActivity.setOnClickListener(view -> {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                searchComment(fragment, true);
            }
        });

        binding.previousResultImageViewViewPostDetailActivity.setOnClickListener(view -> {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                searchComment(fragment, false);
            }
        });

        binding.closeSearchPanelImageViewViewPostDetailActivity.setOnClickListener(view -> {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.resetSearchedPosition();
            }

            binding.searchPanelMaterialCardViewViewPostDetailActivity.setVisibility(View.GONE);
        });
    }

    public boolean isNsfwSubreddit() {
        return mIsNsfwSubreddit;
    }

    private void editComment(Comment comment, int position) {
        if (mSectionsPagerAdapter != null) {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.editComment(comment, position);
            }
        }
    }

    private void editComment(String commentContentMarkdown, int position) {
        if (mSectionsPagerAdapter != null) {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.editComment(commentContentMarkdown, position);
            }
        }
    }

    public void deleteComment(String fullName, int position) {
        if (mSectionsPagerAdapter != null) {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.deleteComment(fullName, position);
            }
        }
    }

    public void toggleReplyNotifications(Comment comment, int position) {
        if (mSectionsPagerAdapter != null) {
            ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
            if (fragment != null) {
                fragment.toggleReplyNotifications(comment, position);
            }
        }
    }

    public void toggleSaveComment(@NonNull Comment comment, int position) {
        ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
        if (fragment != null) {
            fragment.toggleSaveComment(comment, position);
        }
        /*if (comment.isSaved()) {
            comment.setSaved(false);
            SaveThing.unsaveThing(mOauthRetrofit, accessToken, comment.getFullName(), new SaveThing.SaveThingListener() {
                @Override
                public void success() {
                    ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
                    if (fragment != null) {
                        fragment.saveComment(position, false);
                    }
                    Toast.makeText(ViewPostDetailActivity.this, R.string.comment_unsaved_success, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void failed() {
                    ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
                    if (fragment != null) {
                        fragment.saveComment(position, true);
                    }
                    Toast.makeText(ViewPostDetailActivity.this, R.string.comment_unsaved_failed, Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            comment.setSaved(true);
            SaveThing.saveThing(mOauthRetrofit, accessToken, comment.getFullName(), new SaveThing.SaveThingListener() {
                @Override
                public void success() {
                    ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
                    if (fragment != null) {
                        fragment.saveComment(position, true);
                    }
                    Toast.makeText(ViewPostDetailActivity.this, R.string.comment_saved_success, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void failed() {
                    ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
                    if (fragment != null) {
                        fragment.saveComment(position, false);
                    }
                    Toast.makeText(ViewPostDetailActivity.this, R.string.comment_saved_failed, Toast.LENGTH_SHORT).show();
                }
            });
        }*/
    }

    public boolean toggleSearchPanelVisibility() {
        if (binding.searchPanelMaterialCardViewViewPostDetailActivity.getVisibility() == View.GONE) {
            binding.searchPanelMaterialCardViewViewPostDetailActivity.setVisibility(View.VISIBLE);
            return false;
        } else {
            binding.searchPanelMaterialCardViewViewPostDetailActivity.setVisibility(View.GONE);
            binding.searchTextInputEditTextViewPostDetailActivity.setText("");
            return true;
        }
    }

    public void searchComment(ViewPostDetailFragmentNew fragment, boolean searchNextComment) {
        if (!binding.searchTextInputEditTextViewPostDetailActivity.getText().toString().isEmpty()) {
            fragment.searchComment(binding.searchTextInputEditTextViewPostDetailActivity.getText().toString(), searchNextComment);
        }
    }

    public void fetchMorePosts(boolean changePage) {
        viewPostDetailActivityViewModel.fetchMorePosts(
                accessToken, accountName, changePage, postType,
                subredditName, concatenatedSubredditNames, username,
                userWhere, multiPath, query, sortType, sortTime, postFilter,
                readPostType, readPostsList
        );
    }

    public void updatePostFromEvent(Post post, int postListPosition) {

    }

    @Subscribe
    public void onAccountSwitchEvent(SwitchAccountEvent event) {
        if (!getClass().getName().equals(event.excludeActivityClassName)) {
            finish();
        }
    }

    @Subscribe
    public void onProvidePostListToViewPostDetailActivityEvent(ProvidePostListToViewPostDetailActivityEvent event) {
        if (event.postFragmentId == mPostFragmentId && viewPostDetailActivityViewModel.getPosts() == null) {
            viewPostDetailActivityViewModel.setPosts(event.posts);
            this.postType = event.postType;
            this.subredditName = event.subredditName;
            this.concatenatedSubredditNames = event.concatenatedSubredditNames;
            this.username = event.username;
            this.userWhere = event.userWhere;
            this.multiPath = event.multiPath;
            this.query = event.query;
            this.trendingSource = event.trendingSource;
            this.readPostType = event.readPostType;
            this.postFilter = event.postFilter;
            this.sortType = event.sortType.getType();
            this.sortTime = event.sortType.getTime();
            this.readPostsList = event.readPostsList;

            if (mSectionsPagerAdapter != null) {
                if (mPostListPosition > 0)
                    mSectionsPagerAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.view_post_detail_activity, menu);
        applyMenuItemTheme(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            triggerBackPress();
            return true;
        } else if (item.getItemId() == R.id.action_reset_fab_position_view_post_detail_activity) {
            binding.fabViewPostDetailActivity.resetCoordinates();
            return true;
        } else if (item.getItemId() == R.id.action_next_parent_comment_view_post_detail_activity) {
            scrollToNextParentComment();
            return true;
        } else if (item.getItemId() == R.id.action_previous_parent_comment_view_post_detail_activity) {
            scrollToPreviousParentComment();
            return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == EDIT_COMMENT_REQUEST_CODE) {
            if (data != null && resultCode == Activity.RESULT_OK) {
                if (data.hasExtra(EditCommentActivity.RETURN_EXTRA_EDITED_COMMENT)) {
                    editComment((Comment) data.getParcelableExtra(EditCommentActivity.RETURN_EXTRA_EDITED_COMMENT),
                            data.getIntExtra(EditCommentActivity.RETURN_EXTRA_EDITED_COMMENT_POSITION, -1));
                } else {
                    editComment(data.getStringExtra(EditCommentActivity.RETURN_EXTRA_EDITED_COMMENT_CONTENT),
                            data.getIntExtra(EditCommentActivity.RETURN_EXTRA_EDITED_COMMENT_POSITION, -1));
                }
            }
        } else if (requestCode == CommentActivity.WRITE_COMMENT_REQUEST_CODE) {
            if (data != null && resultCode == Activity.RESULT_OK) {
                if (data.hasExtra(RETURN_EXTRA_COMMENT_DATA_KEY)) {
                    ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
                    if (fragment != null) {
                        Comment comment = data.getParcelableExtra(RETURN_EXTRA_COMMENT_DATA_KEY);
                        if (comment != null && comment.getDepth() == 0) {
                            fragment.addComment(comment);
                        } else {
                            String parentFullname = data.getStringExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY);
                            int parentPosition = data.getIntExtra(CommentActivity.EXTRA_PARENT_POSITION_KEY, -1);
                            if (parentFullname != null && parentPosition >= 0) {
                                fragment.addChildComment(comment, parentFullname, parentPosition);
                            }
                        }
                    }
                } else {
                    Toast.makeText(this, R.string.send_comment_failed, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        this.post = viewPostDetailActivityViewModel.getPost();
        this.posts = viewPostDetailActivityViewModel.getPosts();
        Bridge.saveInstanceState(this, outState);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        Bridge.clear(this);
        BigImageViewer.imageLoader().cancelAll();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mVolumeKeysNavigateComments) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_VOLUME_UP:
                    scrollToPreviousParentComment();
                    return true;
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    scrollToNextParentComment();
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void sortTypeSelected(SortType sortType) {
        ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
        if (fragment != null) {
            fragment.changeSortType(sortType);
            binding.toolbarViewPostDetailActivity.setTitle(sortType.getType().fullName);
        }
    }

    @Override
    public void onLongPress() {
        ViewPostDetailFragmentNew fragment = mSectionsPagerAdapter.getCurrentFragment();
        if (fragment != null) {
            fragment.goToTop();
        }
    }

    @Override
    public void lockSwipeRightToGoBack() {
        if (mSliderPanel != null) {
            mSliderPanel.lock();
        }
    }

    @Override
    public void unlockSwipeRightToGoBack() {
        if (mSliderPanel != null) {
            mSliderPanel.unlock();
        }
    }

    public void loadAuthorIcons(List<Comment> comments, UserProfileImagesBatchLoader.LoadIconListener loadIconListener) {
        viewPostDetailActivityViewModel.loadAuthorImages(comments, loadIconListener);
    }

    private class SectionsPagerAdapter extends FragmentStateAdapter {

        public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            ViewPostDetailFragmentNew fragment = new ViewPostDetailFragmentNew();
            Bundle bundle = new Bundle();
            List<Post> posts = viewPostDetailActivityViewModel.getPosts();
            if (posts != null) {
                if (mPostListPosition == position && viewPostDetailActivityViewModel.getPost() != null) {
                    bundle.putInt(ViewPostDetailFragmentNew.EXTRA_POST_LIST_POSITION, position);
                    bundle.putString(ViewPostDetailFragmentNew.EXTRA_SINGLE_COMMENT_ID, getIntent().getStringExtra(EXTRA_SINGLE_COMMENT_ID));
                    bundle.putString(ViewPostDetailFragmentNew.EXTRA_CONTEXT_NUMBER, getIntent().getStringExtra(EXTRA_CONTEXT_NUMBER));
                    bundle.putString(ViewPostDetailFragmentNew.EXTRA_MESSAGE_FULLNAME, getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME));
                } else {
                    if (position >= posts.size()) {
                        MorePostsInfoFragment morePostsInfoFragment = new MorePostsInfoFragment();
                        Bundle moreBundle = new Bundle();
                        moreBundle.putInt(MorePostsInfoFragment.EXTRA_STATUS, mLoadingMorePostsStatus);
                        morePostsInfoFragment.setArguments(moreBundle);
                        return morePostsInfoFragment;
                    }
                    bundle.putInt(ViewPostDetailFragmentNew.EXTRA_POST_LIST_POSITION, position);
                }
            } else {
                if (viewPostDetailActivityViewModel.getPost() == null) {
                    bundle.putString(ViewPostDetailFragmentNew.EXTRA_POST_ID, getIntent().getStringExtra(EXTRA_POST_ID));
                } else {
                    bundle.putInt(ViewPostDetailFragmentNew.EXTRA_POST_LIST_POSITION, mPostListPosition);
                }
                bundle.putString(ViewPostDetailFragmentNew.EXTRA_SINGLE_COMMENT_ID, getIntent().getStringExtra(EXTRA_SINGLE_COMMENT_ID));
                bundle.putString(ViewPostDetailFragmentNew.EXTRA_CONTEXT_NUMBER, getIntent().getStringExtra(EXTRA_CONTEXT_NUMBER));
                bundle.putString(ViewPostDetailFragmentNew.EXTRA_MESSAGE_FULLNAME, getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME));
            }
            fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getItemCount() {
            List<Post> posts = viewPostDetailActivityViewModel.getPosts();
            return posts == null ? 1 : posts.size() + 1;
        }

        @Nullable
        ViewPostDetailFragmentNew getCurrentFragment() {
            if (mFragmentManager == null) {
                return null;
            }
            Fragment fragment = mFragmentManager.findFragmentByTag("f" + binding.viewPager2ViewPostDetailActivity.getCurrentItem());
            if (fragment instanceof ViewPostDetailFragmentNew) {
                return (ViewPostDetailFragmentNew) fragment;
            }
            return null;
        }

        @Nullable
        MorePostsInfoFragment getMorePostsInfoFragment() {
            List<Post> posts = viewPostDetailActivityViewModel.getPosts();
            if (posts == null || mFragmentManager == null) {
                return null;
            }
            Fragment fragment = mFragmentManager.findFragmentByTag("f" + posts.size());
            if (fragment instanceof MorePostsInfoFragment) {
                return (MorePostsInfoFragment) fragment;
            }
            return null;
        }
    }
}
