package com.zhaohaoting.framework.utils;

import com.zhaohaoting.framework.abs.entity.ItemModel;

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

import java.util.List;
import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * author：Created by zhaohaoting on 2018/8/22
 * email：526309416@qq.com
 * desc：LitePal缓存
 */
public class DataSupportCache {

    /**
     * 全部缓存 更新之前的数据
     *
     * @param dataSupports
     * @param consumer
     */
    public static void saveOrUpdateAllAsync(List<? extends ItemModel> dataSupports, Consumer<Integer> consumer) {
        Disposable subscribe = Observable.fromCallable(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int successCount = 0;
                for (ItemModel dataSupport : dataSupports) {
                    boolean orUpdate = dataSupport.saveOrUpdate(dataSupport.getPrimaryKey() + "=?", dataSupport.getPrimaryValue());
                    if (orUpdate) successCount++;
                }
                return successCount;
            }
        }).compose(RxSchedulers.applyObservableCompute()).subscribe(consumer, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Logger.e("缓存失败", throwable.getMessage());
            }
        });
    }

    /**
     * 全部缓存 清除之前的数据
     *
     * @param dataSupports
     * @param clazz
     */
    public static void saveAllAsync(List<? extends ItemModel> dataSupports, Class<? extends ItemModel> clazz, SaveCallback saveCallback, String... whereColumn) {
        DataSupport.deleteAllAsync(clazz, whereColumn).listen(new UpdateOrDeleteCallback() {
            @Override
            public void onFinish(int rowsAffected) {
                DataSupport.saveAllAsync(dataSupports).listen(saveCallback);
                Logger.e("onFinish", Thread.currentThread().getName());
            }
        });
    }
}
