package com.sybotan.android.demo.tools;

import android.content.Context;
import android.text.TextUtils;

import com.sybotan.android.demo.activities.BaseActivity;
import com.sybotan.android.demo.retrofit.BaseViewModelInterface;

import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wangjie on 2019/10/15
 * 利用Observable处理耗时操作时的线程切换类
 * 诸如：本地文件读写、数据库操作等
 */
public class LocalDataOperation {
    //在子线程处理耗时操作
    public static final String DEAL_IO_DATA = "DEAL_IO_DATA";
    //可以具体开始子线程的耗时操作前显示操作等待弹窗之类的
    public static final String SHOW_DIALOG_IN_MAIN = "SHOW_DIALOG_IN_MAIN";
    //子线程数据处理完毕，回到主线程
    public static final String DEAL_DATA_NEXT = "DEAL_DATA_NEXT";
    //子线程数据处理出现异常
    public static final String DEAL_DATA_ERROR = "DEAL_DATA_ERROR";
    //承接查验离线自动上传
    public String ALL_NEED_SUBMIT_CHECK = "ALL_NEED_SUBMIT_CHECK";
    //离线保存的工单待执行列表数据
    public String ALL_NEED_SUBMIT_ORDER = "ALL_NEED_SUBMIT_ORDER";
    //离线数据上传接口类
    public OfflineSendRequest offlineSendRequest;


    private LocalDataOperation() {
        offlineSendRequest = new OfflineSendRequest();
    }

    private static class SingletonHolder {
        private static final LocalDataOperation INSTANCE = new LocalDataOperation();
    }

    public static LocalDataOperation getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 在子线程中处理耗时操作，处理完回到主线程
     *
     * @param mActivity
     * @param object
     * @param <T>
     */
    public <T> void dealLocalData(BaseActivity mActivity, BaseViewModelInterface object) {
        Observable<T> observable = Observable.create((ObservableOnSubscribe<T>) e -> {
            object.SendDircetive(DEAL_IO_DATA, e);
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        observable.compose(mActivity.bindToLifecycle()).subscribe(new Observer<T>() {
            @Override
            public void onSubscribe(Disposable d) {
                object.SendDircetive(SHOW_DIALOG_IN_MAIN, d);
            }

            @Override
            public void onNext(T s) {
                object.SendDircetive(DEAL_DATA_NEXT, s);
            }

            @Override
            public void onError(Throwable e) {
                object.SendDircetive(DEAL_DATA_ERROR, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 离线操作的图片存储路径
     *
     * @param context
     * @return
     */
    public String getOfflineImageFilePath(Context context) {
        return SDCardHelper.getSDCardBaseDir() + "/Android/data/" + context.getPackageName() + "/offlineImages";
    }

}
