package core.ui.common

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.kongzue.dialogx.dialogs.WaitDialog
import http.exception.NetException
import core.ui.widget.decoration.NoLastLineItemDecoration
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import retrofit2.HttpException
import xn.xxp.R
import java.net.ConnectException
import java.net.SocketTimeoutException

/**
 * info
 *
 * @author ReiChin_
 */
class UIDelegateImpl : AbsUIDelegate() {

    override fun showLoading(context: Context, message: String?, cancelable: Boolean) {
        WaitDialog.show(message).setCancelable(cancelable).setEnterAnimDuration(0)
    }

    override fun dismissLoading() {
        WaitDialog.dismiss()
    }

    override fun showToast(context: Context?, message: String) {
        ThreadUtils.runOnUiThread {
            try {
                Toast.makeText(ActivityUtils.getTopActivity(), message, Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                LogUtils.e(Log.getStackTraceString(e))
            }
        }
    }

    override fun showNetError(context: Context?, throwable: Throwable) {
        when (throwable) {
            is NetException -> {
                if (throwable.message.isNullOrEmpty()) {
                    "接口请求失败(${throwable.code})"
                } else {
                    throwable.message!!
                }
            }

            is SocketTimeoutException -> "请求超时，请稍后重试"
            is ConnectException -> "无法连接服务器，请检查网络"
            is HttpException -> "服务器繁忙，请稍后重试"
            else -> null
        }?.let { showToast(context, it) }
    }

    private var mCompositeDisposable: CompositeDisposable? = null

    override fun addDisposable(disposable: Disposable) {
        mCompositeDisposable = (mCompositeDisposable ?: CompositeDisposable()).apply {
            if (!isDisposed) add(disposable)
        }
    }

    override fun removeDisposable(disposable: Disposable) {
        mCompositeDisposable = (mCompositeDisposable ?: CompositeDisposable()).apply {
            remove(disposable)
        }
    }

    override fun clearDisposable() {
        mCompositeDisposable = mCompositeDisposable?.let {
            it.clear()
            null
        }
    }

    override fun createItemDecoration(context: Context?): RecyclerView.ItemDecoration? {
        return context?.let {
            NoLastLineItemDecoration(it, DividerItemDecoration.VERTICAL).apply {
                setDrawable(ContextCompat.getDrawable(it, R.drawable.shape_item_divider)!!)
            }
        }
    }
}