/*
 * Copyright 2016 Christian Schmitz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package simpl.db.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.os.Build;

import simpl.db.SimplDb;
import simpl.db.SimplQuery;
import simpl.db.api.QueryDef;

/**
 * {@code QueryLoader} implements a {@link Loader} for {@link Cursor} returned by a query.
 * <p>
 * This {@code Loader} is aware of changes made to the database through {@link SimplDb}
 * and automatically requeries the data. Loading is always done in a background thread.
 * </p>
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class QueryLoader extends Loader<Cursor> {
    private final Class<? extends QueryDef> mQueryDef;
    private final SimplQuery.Filter mFilter;
    private final SimplDb mDb;
    private Cursor mData;

    private final SimplQuery.Callback mQueryDefCallback = new SimplQuery.Callback() {
        @Override
        public void onQueryFinished(Cursor cursor, Class<? extends QueryDef> queryDef, SimplQuery.Filter filter, SimplDb db) {
            deliverCursor(cursor);
        }
    };

    private final SimplDb.Observer mTableDefObserver = new SimplDb.Observer() {
        @Override
        public void onTableChanged(Class<? extends QueryDef> queryDef, SimplDb db) {
            requestCursor();
        }
    };

    /**
     * @param context  of the application
     * @param queryDef to execute
     * @param db       to use
     */
    public QueryLoader(Context context, Class<? extends QueryDef> queryDef, SimplDb db) {
        this(context, queryDef, null, db);
    }

    /**
     * @param context  of the application
     * @param queryDef to execute
     * @param filter   to apply
     * @param db       to use
     */
    public QueryLoader(Context context, Class<? extends QueryDef> queryDef, SimplQuery.Filter filter, SimplDb db) {
        super(context);
        db.registerObserver(mTableDefObserver, queryDef);
        mQueryDef = queryDef;
        mFilter = filter;
        mDb = db;
    }

    private void setData(Cursor data) {
        if (mData != data) {
            if (mData != null)
                mData.close();
            mData = data;
        }
    }

    void deliverCursor(Cursor data) {
        if (isStarted()) {
            setData(data);
            deliverResult(data);
        }
    }

    void requestCursor() {
        mDb.query(mQueryDef, mFilter, mQueryDefCallback);
    }

    @Override
    protected void onStartLoading() {
        if (mData != null && !mData.isClosed())
            deliverResult(mData);
        else
            requestCursor();
    }

    @Override
    protected void onStopLoading() {
    }

    @Override
    protected void onForceLoad() {
        requestCursor();
    }

    @Override
    protected void onReset() {
        setData(null);
    }
}

@@ -1441,27 +1441,24 @@
 lback mQuery
-Def
 Callback = n
@@ -1621,32 +1621,136 @@
 , SimplDb db) %7B%0A
+            if (!isReset()) %7B%0A                setData(cursor);%0A                if (isStarted())%0A        
             deli
@@ -1752,22 +1752,22 @@
  deliver
-Cursor
+Result
 (cursor)
@@ -1760,32 +1760,46 @@
 Result(cursor);%0A
+            %7D%0A
         %7D%0A    %7D;
@@ -1837,27 +1837,24 @@
 erver mTable
-Def
 Observer = n
@@ -1988,37 +1988,40 @@
             
-requestCursor
+onContentChanged
 ();%0A        
@@ -2590,66 +2590,8 @@
 t);%0A
-        db.registerObserver(mTableDefObserver, queryDef);%0A
     
@@ -2671,24 +2671,16 @@
  %7D%0A%0A    
-private 
 void set
@@ -2841,99 +2841,256 @@
     
-void deliverCursor(Cursor data) %7B%0A        if (isStarted()) %7B%0A            setData(data
+@Override%0A    protected void onStartLoading() %7B%0A        mDb.registerObserver(mTableObserver, mQueryDef);%0A        if (takeContentChanged() %7C%7C mData == null %7C%7C mData.isClosed())%0A            mDb.query(mQueryDef, mFilter, mQueryCallback
 );%0A   
+  
+   else%0A
     
@@ -3086,32 +3086,35 @@
   else%0A         
+   
 deliverResult(da
@@ -3111,17 +3111,18 @@
 rResult(
-d
+mD
 ata);%0A  
@@ -3127,43 +3127,55 @@
     
-  
-  
 %7D
+%0A
 %0A    
-%7D%0A%0A    void requestCursor
+@Override%0A    protected void onForceLoad
 () %7B
@@ -3219,19 +3219,16 @@
 , mQuery
-Def
 Callback
@@ -3266,35 +3266,34 @@
 tected void onSt
-art
+op
 Loading() %7B%0A    
@@ -3300,121 +3300,45 @@
     
-if (mData != null && !mData.isClosed())%0A            deliverResult(mData);%0A        else%0A            requestCursor(
+mDb.unregisterObserver(mTableObserver
 );%0A 
@@ -3374,35 +3374,31 @@
 cted void on
-StopLoading
+Abandon
 () %7B%0A    %7D%0A%0A
@@ -3398,82 +3398,49 @@
     
-%7D%0A%0A
     
-@Override%0A    protected void onForceLoad() %7B%0A        requestCursor(
+mDb.unregisterObserver(mTableObserver
 );%0A 
@@ -3486,24 +3486,72 @@
 onReset() %7B%0A
+        mDb.unregisterObserver(mTableObserver);%0A
         setD

Improve general QueryLoader implementation