package com.remax.visualnovel.app.initializer.impl

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity
import com.remax.visualnovel.app.activityresultapi.XActivityResultContract
import com.remax.visualnovel.app.initializer.AppInitializers
import com.remax.visualnovel.app.viewmodel.AppIMViewModel
import com.remax.visualnovel.configs.NovelApplication
import com.remax.visualnovel.utils.StatusBarUtils
import timber.log.Timber

/**
 * Created by HJW on 2023/5/11
 */
class ActivityLifecycleInitializer(val application: Application, private val appIMViewModel: AppIMViewModel) : AppInitializers {

    override fun init() {
        application.registerActivityLifecycleCallbacks(AppLifecycleCallbacks(appIMViewModel))
    }

    inner class AppLifecycleCallbacks constructor(private val appIMViewModel: AppIMViewModel) : Application.ActivityLifecycleCallbacks {

        private var activityCount = 0

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            if (activity is ActivityResultCaller) {
                //生成一个Key
                val activityKey = activity.javaClass.simpleName + System.currentTimeMillis()
                //添加一个默认ActivityResultLauncher
                val resultLauncher =
                    XActivityResultContract(activity, ActivityResultContracts.StartActivityForResult())
                //把生成的Key放到intent中，作为每一个Activity的唯一标识
                activity.intent.putExtra(KEY_ACTIVITY_RESULT_API, activityKey)
                //存放到Map中
                resultLauncherMap[activityKey] = resultLauncher
            }
        }

        override fun onActivityStarted(activity: Activity) {
            activityCount++
        }

        override fun onActivityPaused(activity: Activity) {
            NovelApplication.setCurrentActivity(null)
        }

        override fun onActivityResumed(activity: Activity) {
            Timber.d("currentActivity:${activity::class.java.name}")
            NovelApplication.setCurrentActivity(activity)
            if (StatusBarUtils.statusBarHeight == 0) {
                StatusBarUtils.getStatusBarHeight(activity)
            }

            //TODO - check pay info later
            /*if (activity !is WelcomeActivity) {
                GooglePayManager.checkProductDetails()
            }*/
        }

        override fun onActivityStopped(activity: Activity) {
            activityCount--
        }

        override fun onActivityDestroyed(activity: Activity) {
            if (activity is FragmentActivity) {
                val activityKey = activity.intent.getStringExtra(KEY_ACTIVITY_RESULT_API)
                if (!TextUtils.isEmpty(activityKey)) {
                    resultLauncherMap[activityKey]?.unregister()
                    //移除activity的resultLauncher
                    resultLauncherMap.remove(activityKey)
                }
            }
        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

        }

    }

    companion object {
        /**
         * 保存ActivityResultApi的Key
         */
        const val KEY_ACTIVITY_RESULT_API = "activityResultApi"

        /**
         * 保存activity和Fragment的resultLauncher
         */
        val resultLauncherMap: MutableMap<String, XActivityResultContract<Intent, ActivityResult>> =
            mutableMapOf()

    }
}