package com.laxture.skeleton.adapter;

import android.os.Build;
import android.widget.ArrayAdapter;

import com.laxture.lib.RuntimeContext;
import com.laxture.lib.task.TaskException;
import com.laxture.lib.task.TaskListener;
import com.laxture.lib.task.TaskManager;
import com.laxture.skeleton.request.AbstractApiTask;

import java.util.List;

public abstract class ApiAdapter<T, ApiResult> extends ArrayAdapter<T>
        implements TaskListener.TaskFinishedListener<ApiResult>,
                   TaskListener.TaskFailedListener<ApiResult> {

    public ApiAdapter() {
        super(RuntimeContext.getApplication(), 0);
    }

    @Override
    public void onTaskFinished(ApiResult result) {
        List<T> resultList = convertApiResultToData(result);
        setArrayData(resultList);
    }

    @Override
    public void onTaskFailed(ApiResult result, TaskException ex) {
        onLoadFailed(ex.getMessage());
    }

    void setArrayData(List<T> data) {
        clear();
        if (Build.VERSION.SDK_INT > 10) {
            addAll(data);
        } else {
            for (T item : data) {
                add(item);
            }
        }
    }

    //*************************************************************************
    // Public Method
    //*************************************************************************

    public void loadData() {
        AbstractApiTask<ApiResult> apiTask = createApiTask();
        apiTask.addFinishedListener(this);
        TaskManager.runImmediately(apiTask);
    }

    //*************************************************************************
    // Abstract Method
    //*************************************************************************

    protected abstract AbstractApiTask<ApiResult> createApiTask();

    protected abstract void onLoadFailed(String errorMessage);

    protected abstract List<T> convertApiResultToData(ApiResult result);

}

@@ -133,16 +133,55 @@
 ontext;%0A
+import com.laxture.lib.java8.Consumer;%0A
 import c
@@ -577,16 +577,60 @@
 ult%3E %7B%0A%0A
+    private Consumer%3CLong%3E mTotalConsumer;%0A%0A
     publ
@@ -1409,24 +1409,141 @@
 **********%0A%0A
+    public void setTotalConsumer(Consumer%3CLong%3E totalConsumer) %7B%0A        this.mTotalConsumer = totalConsumer;%0A    %7D%0A%0A
     public v
@@ -1567,16 +1567,22 @@
         
+final 
 Abstract
@@ -1670,16 +1670,347 @@
 (this);%0A
+        if (mTotalConsumer != null) %7B%0A            apiTask.addFinishedListener(new TaskListener.TaskFinishedListener%3CApiResult%3E() %7B%0A                @Override%0A                public void onTaskFinished(ApiResult apiResult) %7B%0A                    mTotalConsumer.consume(apiTask.getTotal());%0A                %7D%0A            %7D);%0A        %7D%0A
         

Add TotalConsumer to ApiAdapter