package com.yidian.bcommon.mvvm

import android.view.View
import androidx.lifecycle.LifecycleOwner
import com.yidian.bcommon.constant.ResultCode
import com.yidian.bcommon.utils.ToastUtils
import com.yidian.bcommon.widget.LoadingDialog
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.debounce


interface BaseViewComponent<VM : BaseViewModel> {

  val loadingDialog: LoadingDialog

  fun showLoading() {
    loadingDialog.showDialog("努力加载中...")
  }

  fun hideLoading() {
    loadingDialog.hideDialog()
  }

  private fun VM.subscribeErrorEvent(lifecycleOwner: LifecycleOwner) {
    errorEvent.observe(lifecycleOwner) {
      when (it.code) {
        ResultCode.INVALID -> {
          // 特定code分别处理
        }
        else -> {
          if (it.message.isNotBlank()) {
            ToastUtils.showShortSafe(it.message)
          }
        }
      }
    }
  }

  private fun VM.subscribeLoadingEvent(lifecycleOwner: LifecycleOwner) {
    loadingEvent.observe(lifecycleOwner, {
      if (it) {
        showLoading()
      } else {
        hideLoading()
      }
    })
  }


  fun VM.subscribeUiEvent(lifecycleOwner: LifecycleOwner) {
    subscribeLoadingEvent(lifecycleOwner)
    subscribeErrorEvent(lifecycleOwner)
  }
}

@FlowPreview
@ExperimentalCoroutinesApi
fun View.clickAsFlow() = callbackFlow {
  setOnClickListener {
    offer(Unit)
  }
  awaitClose { setOnClickListener(null) }
}.debounce(300)
