package com.rc.core.ui.common

import android.content.Context
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.rc.core.R
import com.rc.core.ui.dialog.LoadingDialog
import com.rc.core.ui.widget.decoration.NoLastLineItemDecoration
import com.rc.httpcore.exception.NetException
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException

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

    private var mPdLoading: LoadingDialog? = null

    override fun showLoading(
        context: Context,
        message: String?,
        cancelable: Boolean
    ) {
        if (null == mPdLoading) {
            mPdLoading = LoadingDialog(context, message)
        }
        mPdLoading?.let {
            it.setMessage(message)
            it.setCancelable(cancelable)
            it.show()
        }
    }

    override fun dismissLoading() {
        mPdLoading?.let {
            it.dismiss()
            mPdLoading = null
        }
    }

    override fun showToast(context: Context?, message: String) {
        context?.let {
            Toast.makeText(it, message, Toast.LENGTH_SHORT).show()
        }
    }

    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 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)!!)
            }
        }
    }
}