package com.example.iot_controlhost.model.thread;

import com.example.iot_controlhost.base.BaseQueue;
import com.example.iot_controlhost.base.IRxIOTask;
import com.example.iot_controlhost.utils.log.MyLog;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.impl.IRxUITask;
import com.xuexiang.rxutil2.rxjava.task.RxUITask;

/**
 * 任务队列-IO与UI任务相继执行
 * @param <T> 任务返回值类型
 */
public abstract class QueueIOUITask<T> extends BaseQueue implements IRxIOTask<T>, IRxUITask<T> {

    @Override
    public void run() {
        try {
            T outData = doInQueueThread();
            RxJavaUtils.doInUIThread(new RxUITask<T>(outData) {
                @Override
                public void doInUIThread(T o) {
                    try {
                        QueueIOUITask.this.doInUIThread(o);
                    } catch (Throwable throwable) {
                        MyLog.appError("队列UI回调异常：异常=" + throwable.getClass().getSimpleName()
                                + "，原因=" + throwable.getMessage());
                        QueueIOUITask.this.onError(throwable);
                    }
                }
            });
        } catch (Throwable throwable) {
            MyLog.controllerError("队列任务执行异常：异常=" + throwable.getClass().getSimpleName()
                    + "，原因=" + throwable.getMessage());
            RxJavaUtils.doInUIThread(new RxUITask<Object>(null) {
                @Override
                public void doInUIThread(Object o) {
                    QueueIOUITask.this.onError(throwable);
                }
            });
        }
    }

    /**
     * IO任务或UI回调失败时执行，默认只记录日志；需要清理界面的任务可重写。
     */
    public void onError(Throwable throwable) {
    }

}
