package lt.vilnius.tvarkau.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

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

import javax.inject.Inject;
import javax.inject.Singleton;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import butterknife.BindView;
import butterknife.ButterKnife;
import lt.vilnius.tvarkau.API.ApiMethod;
import lt.vilnius.tvarkau.API.ApiRequest;
import lt.vilnius.tvarkau.API.ApiResponse;
import lt.vilnius.tvarkau.API.GetProblemsParams;
import lt.vilnius.tvarkau.API.LegacyApiModule;
import lt.vilnius.tvarkau.API.LegacyApiService;
import lt.vilnius.tvarkau.events_listeners.EndlessRecyclerViewScrollListener;
import lt.vilnius.tvarkau.R;
import lt.vilnius.tvarkau.entity.Problem;
import lt.vilnius.tvarkau.views.adapters.ProblemsListAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Karolis Vycius on 2016-01-13.
 */

@AutoComponent(modules = LegacyApiModule.class)
@AutoInjector
@Singleton
public class ProblemsListFragment extends Fragment {

    @Inject LegacyApiService legacyApiService;

    @BindView(R.id.swipe_container) SwipeRefreshLayout swipeContainer;
    @BindView(R.id.problem_list) RecyclerView recyclerView;

    public static final int PROBLEM_COUNT_LIMIT_PER_PAGE = 100;
    public List<Problem> problemList;
    public ProblemsListAdapter adapter;

    public static ProblemsListFragment getInstance() {
        return new ProblemsListFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        problemList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.problem_list, container, false);

        ButterKnife.bind(this, view);

        DaggerProblemsListFragmentComponent.create().inject(this);

        swipeContainer.setOnRefreshListener(() -> getData(0));
        swipeContainer.setColorSchemeResources(R.color.colorAccent);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) {
            @Override public void onLoadMore(int page, int totalItemsCount) {
                getData(page);
            }
        });

        adapter = new ProblemsListAdapter(getActivity(), problemList);
        recyclerView.setAdapter(adapter);

        getData(0);

        return view;
    }

    private void setupView() {
        adapter.notifyDataSetChanged();
    }

    private void getData(int page) {

        int startLoadingFromPage = page * PROBLEM_COUNT_LIMIT_PER_PAGE;

        GetProblemsParams params = new GetProblemsParams(startLoadingFromPage, PROBLEM_COUNT_LIMIT_PER_PAGE,
            null, null, null, null, null, null);
        ApiRequest<GetProblemsParams> request = new ApiRequest<>(ApiMethod.GET_PROBLEMS, params);

        Action1<ApiResponse<List<Problem>>> onSuccess = apiResponse -> {
            if (apiResponse.getResult().size() > 0) {
                problemList.addAll(apiResponse.getResult());
                setupView();
                swipeContainer.setRefreshing(false);
            } else {
                Toast.makeText(getContext(), R.string.error_no_problems_in_list, Toast.LENGTH_SHORT).show();
            }
        };

        Action1<Throwable> onError = Throwable::printStackTrace;

        legacyApiService.getProblems(request)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                onSuccess,
                onError
            );
    }
}

@@ -657,16 +657,45 @@
 rKnife;%0A
+import butterknife.Unbinder;%0A
 import l
@@ -727,16 +727,16 @@
 Method;%0A
-
 import l
@@ -1276,16 +1276,63 @@
 edulers;
+%0Aimport rx.subscriptions.CompositeSubscription;
 %0A%0A/**%0A *
@@ -1826,16 +1826,96 @@
 adapter;
+%0A    private Unbinder unbinder;%0A    private CompositeSubscription subscriptions;
 %0A%0A    pu
@@ -2166,16 +2166,75 @@
 ist%3C%3E();
+%0A        subscriptions = new CompositeSubscription();%0A    %7D
 %0A%0A    @N
@@ -2466,16 +2466,27 @@
 %0A       
+ unbinder =
  ButterK
@@ -4417,16 +4417,16 @@
 onError%0A
-
         
@@ -4437,11 +4437,343 @@
 );%0A    %7D
+%0A%0A    @Override%0A    public void onDestroyView() %7B%0A        super.onDestroyView();%0A        unbinder.unbind();%0A    %7D%0A%0A    @Override%0A    public void onPause() %7B%0A        super.onPause();%0A        if (subscriptions != null) %7B%0A            subscriptions.unsubscribe();%0A            subscriptions = new CompositeSubscription();%0A        %7D%0A    %7D
 %0A%7D%0A

Add unbinder (Butterknife) and subscription (rxJava) management for ProblemListFragment