package cn.muchinfo.rma.view.autoWidget


import androidx.lifecycle.GenericLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.NetworkUtils
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.sql.SQLException
import java.text.ParseException

fun <T> Observable<T>.applySchedulers(): Observable<T> {
    return this.subscribeOn(io.reactivex.schedulers.Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
}

fun <T> Flowable<T>.applySchedulers(): Flowable<T> {
    return this.subscribeOn(io.reactivex.schedulers.Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
}

fun <T> Observable<T>.bindLifeCycle(lifecycleOwner: LifecycleOwner?, event: Lifecycle.Event = Lifecycle.Event.ON_DESTROY): Observable<T> {
    if (lifecycleOwner != null) {
        return doOnSubscribe {
            lifecycleOwner.lifecycle.addObserver(GenericLifecycleObserver { _, e ->
                if (event == e) {
                    it.dispose()
                }
            })
        }
    }
    return this
}

fun <T> Flowable<T>.bindLifeCycle(lifecycleOwner: LifecycleOwner?, event: Lifecycle.Event = Lifecycle.Event.ON_DESTROY): Flowable<T> {
    if (lifecycleOwner != null) {
        return doOnSubscribe {
            lifecycleOwner.lifecycle.addObserver(GenericLifecycleObserver { _, e ->
                if (event == e) {
                    it.cancel()
                }
            })
        }
    }
    return this
}

//fun <T> Observable<T>.onHandleCommonError(): Observable<T> {
//    return onErrorResumeNext(Function { throwable ->
////        Timber.e(throwable)
//        ObservableSource<T> {
//            val error = when (throwable) {
//                is SocketTimeoutException,
//                is ConnectException,
//                is IOException,
//                is HttpException -> APIException(APIException.ERROR_CODE_NET_ENABLE, "")
//                is IllegalArgumentException,
//                is ParseException,
//                is android.database.SQLException,
//                is SQLException -> DataException(DataException.PARSE_ERROR)
//                else -> {
//                    if (NetworkUtils.isConnected().not()) {
//                        APIException(APIException.ERROR_CODE_NET_ENABLE, "")
//                    } else {
//                        throwable
//                    }
//                }
//            }
//            it.onError(error)
//        }
//    })
//}
