package com.veyndan.hermes;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;
import com.veyndan.hermes.database.DbHelper;
import com.veyndan.hermes.home.HomeAdapter;
import com.veyndan.hermes.home.model.Comic;
import com.veyndan.hermes.service.ComicService;
import com.veyndan.hermes.ui.AutoStaggeredGridLayoutManager;

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

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class FeedFragment extends BaseFragment {

    private static final String TAG = "veyndan_FeedFragment";

    private final List<Comic> comics = new ArrayList<>();
    private final HomeAdapter adapter = new HomeAdapter(comics);

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

    public static FeedFragment newInstance() {
        return new FeedFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        RecyclerView recyclerView =
                (RecyclerView) inflater.inflate(R.layout.feed_fragment, container, false);
        recyclerView.setLayoutManager(new AutoStaggeredGridLayoutManager(700));
        recyclerView.setAdapter(adapter);

        ComicService comicService = new ComicService();

        SqlBrite sqlBrite = SqlBrite.create();
        BriteDatabase db = sqlBrite.wrapDatabaseHelper(new DbHelper(getActivity()), Schedulers.io());

        String sql = SQLiteQueryBuilder.buildQueryString(false, Comic.TABLE, null, null, null, null, Comic.NUM + " DESC", "1");
        db.createQuery(Comic.TABLE, sql)
                .compose(this.<SqlBrite.Query>bindToLifecycle())
                .flatMap(query -> query.asRows(Comic.MAPPER))
                .flatMap(comic -> comicService.fetchComics(comic.num()))
                .switchIfEmpty(comicService.fetchComics())
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(comic -> Log.d(TAG, "onCreateView:" + comic));

//        db.createQuery(Comic.TABLE, "SELECT * FROM " + Comic.TABLE)
//                .compose(this.<SqlBrite.Query>bindToLifecycle())
//                .concatMap(query -> query.asRows(Comic.MAPPER))
//                .concatWith(db.createQuery(Comic.TABLE, "SELECT MAX(_id) FROM " + Comic.TABLE)
//                        .flatMap(query -> query.asRows(Comic.MAPPER))
//                        .flatMap(comic -> comicService.fetchComics(comic.num())))
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(comic -> {
//                    comics.add(comic);
//                    adapter.notifyDataSetChanged();
//                });
//
        comicService.fetchComics(1600, 1650)
                .compose(this.<Comic>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(comic -> {
                    db.insert(Comic.TABLE, comic.toContentValues(comic), SQLiteDatabase.CONFLICT_IGNORE);
                    comics.add(comic);
                    adapter.notifyDataSetChanged();
                });

        return recyclerView;
    }
}

@@ -73,59 +73,8 @@
 se;%0A
-import android.database.sqlite.SQLiteQueryBuilder;%0A
 impo
@@ -95,16 +95,16 @@
 Bundle;%0A
+
 import a
@@ -146,33 +146,8 @@
 ew;%0A
-import android.util.Log;%0A
 impo
@@ -1702,24 +1702,26 @@
 ers.io());%0A%0A
+//
         Stri
@@ -1836,16 +1836,18 @@
 , %221%22);%0A
+//
         
@@ -1879,16 +1879,18 @@
 E, sql)%0A
+//
         
@@ -1938,32 +1938,34 @@
 dToLifecycle())%0A
+//
                 
@@ -2010,16 +2010,18 @@
 APPER))%0A
+//
         
@@ -2085,16 +2085,18 @@
 num()))%0A
+//
         
@@ -2142,24 +2142,26 @@
 chComics())%0A
+//
             
@@ -2184,32 +2184,34 @@
 chedulers.io())%0A
+//
                 
@@ -2247,32 +2247,34 @@
 s.mainThread())%0A
+//
                 
@@ -3102,9 +3102,9 @@
 , 16
-5
+6
 0)%0A 
@@ -3154,24 +3154,52 @@
 ifecycle())%0A
+                .buffer(20)%0A
             
@@ -3323,22 +3323,24 @@
 be(comic
+s
  -%3E %7B%0A
+%0A
         
@@ -3355,114 +3355,465 @@
     
-db.insert(Comic.TABLE, comic.toContentValues(comic), SQLiteDatabase.CONFLICT_IGNORE);%0A                    
+BriteDatabase.Transaction transaction = db.newTransaction();%0A                    try %7B%0A                        for (Comic comic : comics) %7B%0A                            db.insert(Comic.TABLE, comic.toContentValues(comic), SQLiteDatabase.CONFLICT_IGNORE);%0A                        %7D%0A                        transaction.markSuccessful();%0A                    %7D finally %7B%0A                        transaction.end();%0A                    %7D%0A%0A                    this.
 comi
@@ -3818,22 +3818,26 @@
 mics.add
+All
 (comic
+s
 );%0A     

Set buffer size so database transactions and adapter insertions can be done in bulk