package com.veyndan.redditclient.post;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jakewharton.rxbinding.support.v7.widget.RxRecyclerView;
import com.veyndan.redditclient.Config;
import com.veyndan.redditclient.R;
import com.veyndan.redditclient.Tree;
import com.veyndan.redditclient.UserFilter;
import com.veyndan.redditclient.api.reddit.Reddit;
import com.veyndan.redditclient.api.reddit.network.Credentials;
import com.veyndan.redditclient.post.model.Post;
import com.veyndan.redditclient.ui.recyclerview.SwipeItemTouchHelperCallback;
import com.veyndan.redditclient.ui.recyclerview.itemdecoration.MarginItemDecoration;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;

public class PostsFragment extends Fragment implements PostMvpView {

    private static final String ARG_USER_FILTER = "user_filter";

    private final PostPresenter postPresenter = new PostPresenter();

    private RecyclerView recyclerView;

    private final List<Tree.Node<Post>> nodes = new ArrayList<>();

    private PostAdapter postAdapter;

    private LinearLayoutManager layoutManager;

    private boolean loadingPosts;
    private int pastVisiblesItems, visibleItemCount, totalItemCount;

    private Reddit reddit;

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

    public static PostsFragment newInstance(final UserFilter userFilter) {
        final PostsFragment fragment = new PostsFragment();

        final Bundle args = new Bundle();
        args.putParcelable(ARG_USER_FILTER, userFilter);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onAttach(final Context context) {
        super.onAttach(context);
        postPresenter.attachView(this);

        final Credentials credentials = new Credentials(Config.REDDIT_CLIENT_ID_RAWJAVA, Config.REDDIT_CLIENT_SECRET, Config.REDDIT_USER_AGENT, Config.REDDIT_USERNAME, Config.REDDIT_PASSWORD);
        reddit = new Reddit.Builder(credentials).build();
    }

    @Override
    public void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    public void setFilter(final PostsFilter filter) {
        clearPosts();
        nodes.add(new Tree.Node<>(null, true));
        postPresenter.loadPosts(filter, getNextPageTrigger());
    }

    public void clearPosts() {
        final int postsSize = this.nodes.size();
        this.nodes.clear();
        if (postAdapter != null) {
            postAdapter.notifyItemRangeRemoved(0, postsSize);
        }
    }

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

        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new MarginItemDecoration(getActivity(), R.dimen.card_view_margin));
        postAdapter = new PostAdapter(getActivity(), nodes, reddit);
        recyclerView.setAdapter(postAdapter);

        final ItemTouchHelper.Callback swipeCallback = new SwipeItemTouchHelperCallback();
        final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(swipeCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);

        final Bundle args = getArguments();
        if (args != null) {
            setFilter(args.getParcelable(ARG_USER_FILTER));
        }

        return recyclerView;
    }

    @Override
    public void onDestroy() {
        postPresenter.detachView();
        super.onDestroy();
    }

    @Override
    public void showPosts(final List<Tree.Node<Post>> nodes) {
        final int positionStart = this.nodes.size();
        this.nodes.addAll(this.nodes.size() - 1, nodes);
        postAdapter.notifyItemRangeInserted(positionStart, nodes.size());
        loadingPosts = false;
    }

    @Override
    public void removeProgressBar() {
        final int progressBarIndex = nodes.size() - 1;
        nodes.remove(progressBarIndex);
        postAdapter.notifyItemRemoved(progressBarIndex);
    }

    public Observable<Boolean> getNextPageTrigger() {
        return RxRecyclerView.scrollEvents(recyclerView)
                .filter(scrollEvent -> scrollEvent.dy() > 0) //check for scroll down
                .map(scrollEvent -> {
                    visibleItemCount = layoutManager.getChildCount();
                    totalItemCount = layoutManager.getItemCount();
                    pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
                    return scrollEvent;
                })
                .filter(scrollEvent -> !loadingPosts && visibleItemCount + pastVisiblesItems >= totalItemCount)
                .map(scrollEvent -> {
                    loadingPosts = true;
                    return true;
                });
    }
}

@@ -1491,77 +1491,8 @@
 sts;
-%0A    private int pastVisiblesItems, visibleItemCount, totalItemCount;
 %0A%0A  
@@ -4780,35 +4780,92 @@
                .
-map
+filter(scrollEvent -%3E !loadingPosts)%0A                .filter
 (scrollEvent -%3E 
@@ -4886,16 +4886,26 @@
         
+final int 
 visibleI
@@ -4911,37 +4911,36 @@
 ItemCount = 
-layoutManager
+recyclerView
 .getChildCou
@@ -4965,16 +4965,26 @@
         
+final int 
 totalIte
@@ -5042,18 +5042,29 @@
         
-pa
+final int fir
 stVisibl
@@ -5064,22 +5064,20 @@
 tVisible
-s
 Item
-s
  = layou
@@ -5148,95 +5148,24 @@
 urn 
-scrollEvent;%0A                %7D)%0A                .filter(scrollEvent -%3E !loadingPosts &&
+totalItemCount -
  vis
@@ -5182,12 +5182,14 @@
 unt 
-+ pa
+%3C= fir
 stVi
@@ -5197,32 +5197,31 @@
 ible
-s
 Item
-s %3E= totalItemCount
+;%0A                %7D
 )%0A  

Make global fields which can be local, local