package com.gh.gamecenter.core.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.GHThreadFactory
import com.gh.gamecenter.core.HaloApp
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * 统计用户在当前 Fragment/Activity 的停留时间，在 onViewDestroy 或 onDestroy 里获取 elapsedTime 即可，单位为秒
 */
class TimeElapsedHelper(val fragment: Fragment?, val activity: Activity?) {

    constructor() : this(null, null)

    constructor(fragment: Fragment) : this(fragment, null)

    constructor(activity: Activity) : this(null, activity)

    private var isWorking = false

    var elapsedTime: Int = 0

    var timeout: Int = 0
    var timeoutCallback: TimeoutCallback? = null

    init {
        activity?.application?.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityStarted(a: Activity) {
            }

            override fun onActivitySaveInstanceState(a: Activity, outState: Bundle) {
            }

            override fun onActivityStopped(a: Activity) {
            }

            override fun onActivityCreated(a: Activity, savedInstanceState: Bundle?) {
            }

            override fun onActivityPaused(a: Activity) {
                if (activity == a) {
                    pauseCounting()
                }
            }

            override fun onActivityResumed(a: Activity) {
                if (activity == a) {
                    resumeCounting()
                }
            }

            override fun onActivityDestroyed(a: Activity) {
                if (activity == a) {
                    HaloApp.getInstance().unregisterActivityLifecycleCallbacks(this)
                }
            }
        })

        fragment?.fragmentManager?.registerFragmentLifecycleCallbacks(
            object : FragmentManager.FragmentLifecycleCallbacks() {
                override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
                    if (f === fragment) {
                        resumeCounting()
                    }
                }

                override fun onFragmentPaused(fm: FragmentManager, f: Fragment) {
                    if (f === fragment) {
                        pauseCounting()
                    }
                }

                override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) {
                    if (f === fragment) {
                        fragment.fragmentManager?.unregisterFragmentLifecycleCallbacks(this)
                    }
                }
            }, false
        )
    }

    fun resumeCounting() {
        isWorking = true
        TimeElapsedThreadHolder.threadService.execute {
            while (isWorking) {
                try {
                    elapsedTime++
                    if (timeout != 0 && timeout == elapsedTime) {
                        timeoutCallback?.run {
                            AppExecutor.uiExecutor.execute {
                                onTimeout()
                            }
                        }
                    }
                    Thread.sleep(1000)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    fun resetCounting() {
        elapsedTime = 0
    }

    fun pauseCounting() {
        isWorking = false
    }

}

object TimeElapsedThreadHolder {
    val threadService: ExecutorService by lazy { Executors.newSingleThreadExecutor(GHThreadFactory("TIME_ELAPSED_THREAD")) }
}

interface TimeoutCallback {
    fun onTimeout()
}