package com.zhaohaoting.framework.abs.datasource;

import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource;
import com.zhaohaoting.framework.mvchelper.mvc.IDataAdapter;
import com.zhaohaoting.framework.mvchelper.mvc.IDataCacheLoader;
import com.zhaohaoting.framework.mvchelper.mvc.RequestHandle;
import com.zhaohaoting.framework.mvchelper.mvc.ResponseSender;
import com.zhaohaoting.framework.requset.ResultCallback;

import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.SaveCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;

/**
 * author：Created by ZHT on 2017/11/13 14:17
 * email：526309416@qq.com
 * desc：列表 RESULT_DATA为BaseListEntity<DATA>或List<DATA></>
 */
@Deprecated
@SuppressWarnings("unchecked")
public abstract class BaseListDataSource<DATA, RESULT_DATA> implements IAsyncDataSource<RESULT_DATA>, IDataCacheLoader<RESULT_DATA> {
    protected int pageNumber = 1;//页码
    protected int pageSize = 10;//每页大小
    protected int currentTotal = 0;
    private Class<DATA> tCls;
    private Class<RESULT_DATA> resultCls;
    protected String column = "";//"createTime desc"
    protected boolean canUseCache = false;//此列表是否做缓存
    protected boolean isPaging = true;//此列表是否分页

    public BaseListDataSource() {
        tCls = ((Class<DATA>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
        resultCls = (Class<RESULT_DATA>) ((ParameterizedType) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).getRawType();
//        resultCls = (Class<RESULT_DATA>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    @Override
    public RequestHandle loadMore(ResponseSender<RESULT_DATA> sender) throws Exception {
        return loadDataSource(sender, pageNumber + 1);
    }

    @Override
    public RequestHandle refresh(ResponseSender<RESULT_DATA> sender) throws Exception {
        pageNumber = 1;
        return loadDataSource(sender, 1);
    }

    @Override
    public boolean hasMore() {
        return currentTotal == pageSize;
    }

    @Override
    public RESULT_DATA loadCache(IDataAdapter<RESULT_DATA> adapter) {//当adapter.isEmpty() 加载缓存
        if (adapter.isEmpty() && canUseCache) {
//                RESULT_DATA result_data = resultCls.isAssignableFrom().newInstance();
//            if (resultCls.isAssignableFrom(BaseListEntity.class)) {
//                BaseListEntity<DATA> notifyBaseListEntity = new BaseListEntity<DATA>();
//                notifyBaseListEntity.setRows(DataSupport.order(column).find(tCls));
//                return (RESULT_DATA) notifyBaseListEntity;
//            }
            if (resultCls.isAssignableFrom(List.class)) {
                List<DATA> dataList = DataSupport.order(column).find(tCls);
                return (RESULT_DATA) dataList;
            }
            throw new RuntimeException("RESULT_DATA Type error");
        }
        return null;
    }

    @Override
    public void setCache(final RESULT_DATA notifyBaseListEntity) {
        if (!canUseCache) return;
        if (DataSupport.class.isAssignableFrom(tCls)) {
            DataSupport.deleteAllAsync(tCls).listen(new UpdateOrDeleteCallback() {
                @Override
                public void onFinish(int rowsAffected) {
                    /*if (notifyBaseListEntity instanceof BaseListEntity) {
                        DataSupport.saveAllAsync(((BaseListEntity<ItemModel>) notifyBaseListEntity).getRows()).listen(new SaveCallback() {
                            @Override
                            public void onFinish(boolean success) {
//                        Logger.e("success",success+"");
                            }
                        });
                    } else */if (notifyBaseListEntity instanceof List) {
                        DataSupport.saveAllAsync((List<DataSupport>) notifyBaseListEntity).listen(new SaveCallback() {
                            @Override
                            public void onFinish(boolean success) {
//                        Logger.e("success",success+"");
                            }
                        });
                    }

                }
            });
        }
    }

    private RequestHandle loadDataSource(ResponseSender<RESULT_DATA> sender, final int page) {
        HashMap<String, Object> params = new HashMap<>();
        if (isPaging) {
            params.put("pageNumber", page);
            params.put("pageSize", pageSize);
        }
        return loadListFromNetWork(params, sender, new ResultCallback.RequestCallback<RESULT_DATA>() {
            @Override
            public void requestSuccess(RESULT_DATA dataSource) {
                if (dataSource instanceof List) {
                    currentTotal = ((List)dataSource).size();
                    pageNumber = page;
                }
            }
        });
    }

    protected abstract RequestHandle loadListFromNetWork(HashMap<String, Object> params, ResponseSender<RESULT_DATA> sender, ResultCallback.RequestCallback<RESULT_DATA> requestCallback);
}
