package com.gh.common.util

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.core.GHThreadFactory
import com.gh.gamecenter.MainActivity
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.common.utils.isPublishEnv
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailActivity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

object BbsStayTimeHelper {

    private var mStayTimeCount = 0
    private var mIsStayTimeCountEnabled = false // 论坛停留时间统计是否开启
    private var mStayTimeTimeout = 30
    private var mIsStayTimeCountValid = false // 论坛停留时间统计是否有效

    const val IS_BBS_CONTENT_VISIBLE = "is_bbs_content_visible"

    private val mThreadService: ExecutorService by lazy {
        Executors.newSingleThreadExecutor(GHThreadFactory("STAY_TIME_THREAD"))
    }

    private val mActivityLifecycleCallbacks by lazy {
        object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
            override fun onActivityStarted(activity: Activity) {}

            override fun onActivityResumed(activity: Activity) {
                if (isTopActivityBbsRelated(activity) && mIsStayTimeCountEnabled) {
                    resumeTimeCount()
                }
            }

            override fun onActivityPaused(activity: Activity) {
                if (isTopActivityBbsRelated(activity) && mIsStayTimeCountEnabled) {
                    pauseTimeCount()
                }
            }
        }
    }

    fun enableStayTimeCount(timeout: Int) {
        mIsStayTimeCountEnabled = true
        mStayTimeTimeout = timeout

        resumeTimeCount()

        HaloApp.getInstance().registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks)
    }

    fun disableStayTimeCount() {
        mIsStayTimeCountEnabled = false
        mStayTimeCount = 0

        HaloApp.getInstance().unregisterActivityLifecycleCallbacks(mActivityLifecycleCallbacks)
    }

    fun resumeTimeCount() {
        if (!mIsStayTimeCountEnabled) return

        mIsStayTimeCountValid = true

        mThreadService.execute {
            while (mIsStayTimeCountEnabled && mIsStayTimeCountValid) {
                val topActivity = CurrentActivityHolder.getCurrentActivity() ?: continue
                if (isTopActivityBbsRelated(topActivity)) {
                    tryWithDefaultCatch {
                        mStayTimeCount++
                        if (mStayTimeCount >= mStayTimeTimeout) {
                            postExploreFinish()
                        }
                    }
                }
                Thread.sleep(1000)
            }
        }
    }

    fun pauseTimeCount() {
        if (!mIsStayTimeCountEnabled) return

        mIsStayTimeCountValid = false
    }

    private fun isTopActivityBbsRelated(activity: Activity): Boolean {
        return (activity is MainActivity && activity.intent.extras?.getBoolean(IS_BBS_CONTENT_VISIBLE) == true)
                || activity is ForumDetailActivity
                || activity is ArticleDetailActivity
                || activity is ForumVideoDetailActivity
                || activity is CommentActivity
                || activity is NewQuestionDetailActivity
    }

    @SuppressLint("CheckResult")
    private fun postExploreFinish() {
        RetrofitManager.getInstance()
            .api
            .postExplorerFinish()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    if (!isPublishEnv()) {
                        ToastUtils.toast("完成了论坛停留任务（仅测试环境有这个 toast 不要慌）")
                    }
                    disableStayTimeCount()
                }
            })
    }

}