package com.veyndan.hermes.home;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.QueryObservable;
import com.squareup.sqlbrite.SqlBrite;
import com.veyndan.hermes.BaseActivity;
import com.veyndan.hermes.R;
import com.veyndan.hermes.database.Db;
import com.veyndan.hermes.database.DbHelper;
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.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class HomeActivity extends BaseActivity {

    private static final String TAG = "veyndan_HomeActivity";

    private static final int BUFFER_SIZE = 20;

    @BindView(R.id.recycler_view) RecyclerView recyclerView;

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

    private BriteDatabase db;
    private List<Integer> filters = new ArrayList<>(2);
    private Subscription databaseSubscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_activity);
        ButterKnife.bind(this);

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

        adapter = new HomeAdapter(comics, db);

        recyclerView.setLayoutManager(new AutoStaggeredGridLayoutManager(700));
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator() {
            @Override
            public boolean canReuseUpdatedViewHolder(@NonNull RecyclerView.ViewHolder viewHolder) {
                // Allows animations to persist through notification of data set change.
                return true;
            }
        });

        ComicService comicService = new ComicService();

        query();

        Observable<List<Comic>> network = comicService.fetchComics(1, 40)
                .buffer(BUFFER_SIZE)
                .doOnNext(comics -> {
                    Db.insert(db, comics);
                    Log.d(TAG, "Network request: " + comics.get(0).num() + " to " + comics.get(comics.size() - 1).num());
                });

//        network
//                .compose(this.<List<Comic>>bindToLifecycle())
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(comics -> {
//                    this.comics.addAll(comics);
//                    adapter.notifyDataSetChanged();
//                });
    }

    private void query() {
        if (databaseSubscription != null) databaseSubscription.unsubscribe();

        QueryObservable database;
        if (filters.contains(R.id.action_filter_favorites)) {
            database = db.createQuery(Comic.TABLE, String.format("SELECT * FROM %s WHERE %s ORDER BY %s DESC", Comic.TABLE, Comic.FAVORITE, Comic.NUM));
        } else {
            database = db.createQuery(Comic.TABLE, String.format("SELECT * FROM %s ORDER BY %s DESC", Comic.TABLE, Comic.NUM));
        }

        databaseSubscription = database
                .compose(this.<SqlBrite.Query>bindToLifecycle())
                .concatMap(query -> query.asRows(Comic.MAPPER).toList())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(comics -> {
                    this.comics.clear();
                    this.comics.addAll(comics);
                    adapter.notifyDataSetChanged();
                });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_filter_favorites:
                item.setChecked(!item.isChecked());
                if (item.isChecked()) filters.add(item.getItemId());
                else filters.remove(Integer.valueOf(item.getItemId()));
                query();
                return true;
            case R.id.action_filter_unread:
                item.setChecked(!item.isChecked());
                return true;
            case R.id.action_sort_new:
            case R.id.action_sort_old:
                // If the item is already checked, then the direction of the list is correct as is.
                if (item.isChecked()) return false;
                item.setChecked(true);
                Collections.reverse(comics);
                adapter.notifyDataSetChanged();
                return true;
            case R.id.action_settings:
                return true;
            default:
                return false;
        }
    }
}

@@ -27,16 +27,67 @@
 .home;%0A%0A
+import android.database.sqlite.SQLiteQueryBuilder;%0A
 import a
@@ -244,24 +244,55 @@
 cyclerView;%0A
+import android.text.TextUtils;%0A
 import andro
@@ -409,54 +409,8 @@
 se;%0A
-import com.squareup.sqlbrite.QueryObservable;%0A
 impo
@@ -1183,16 +1183,109 @@
  = 20;%0A%0A
+    private static final String SELECT_FAVORITES = String.format(%22%25s = 1%22, Comic.FAVORITE);%0A%0A
     @Bin
@@ -1477,23 +1477,22 @@
 te List%3C
-Integer
+String
 %3E filter
@@ -3281,403 +3281,168 @@
     
-QueryObservable database;%0A        if (filters.contains(R.id.action_filter_favorites)) %7B%0A            database = db.createQuery(Comic.TABLE, String.format(%22SELECT * FROM %25s WHERE %25s ORDER BY %25s DESC%22, Comic.TABLE, Comic.FAVORITE, Comic.NUM));%0A        %7D else %7B%0A            database = db.createQuery(Comic.TABLE, String.format(%22SELECT * FROM %25s ORDER BY %25s DESC%22, Comic.TABLE, Comic.NUM));%0A        %7D
+String sql = SQLiteQueryBuilder.buildQueryString(false, Comic.TABLE, null,%0A                TextUtils.join(%22 %22, filters), null, null, Comic.NUM + %22 DESC%22, null);
 %0A%0A  
@@ -3471,23 +3471,47 @@
 tion = d
-atabase
+b.createQuery(Comic.TABLE, sql)
 %0A       
@@ -4317,32 +4317,32 @@
 ers.add(
-item.getItemId()
+SELECT_FAVORITES
 );%0A     
@@ -4376,41 +4376,24 @@
 ove(
-Integer.valueOf(item.getItemId())
+SELECT_FAVORITES
 );%0A 

Make creation of where clause in query more generic