package com.adealink.weparty.joinus

import androidx.fragment.app.FragmentActivity
import com.adealink.frame.base.Rlt
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.log.Log
import com.adealink.frame.router.Router
import com.adealink.frame.router.interceptor.UriInterceptor
import com.adealink.weparty.App
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.isFailure
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.joinus.data.TAG_JOINUS
import com.adealink.weparty.joinus.datasource.remote.JoinUsHttpService
import com.adealink.weparty.module.joinus.JoinUs
import com.adealink.weparty.module.webview.Web
import com.adealink.weparty.url.UrlConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class JoinUsInterceptor : UriInterceptor {

    private val joinUsHttpService by lazy {
        App.instance.networkService.getHttpService(JoinUsHttpService::class.java)
    }

    override fun intercept(chain: UriInterceptor.Chain) {
        val request = chain.request()
        val activity = request.ctx as? FragmentActivity
        if (activity == null) {
            Log.e(TAG_JOINUS, "JoinUsInterceptor, activity is null")
            return
        }
        CoroutineScope(Dispatcher.UI).launch {
            val skipGuide = request.intent.getBooleanExtra(JoinUs.JoinUs.EXTRA_SKIP_GUIDE, false)
            //进入引导
            if (!skipGuide) {
                Router.build(activity, Web.FullScreen.PATH)
                    .putExtra(Web.Common.EXTRA_URL, UrlConfig.playmateApply)
                    .start()
                chain.abort()
                return@launch
            }

            (activity as? BaseActivity)?.showLoading()
            val rlt = joinUsHttpService.loadJoinUsProgress()
            (activity as? BaseActivity)?.dismissLoading()
            if (rlt.isFailure) {
                showFailedToast(rlt)
                chain.abort()
                return@launch
            }
            val joinProgressData = (rlt as Rlt.Success).data.data
            //进入申请流程
            request.intent.putExtra(JoinUs.Common.EXTRA_JOIN_US, joinProgressData)
            chain.proceed(request)

        }
    }

}