package com.za.base

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import android.view.WindowManager
import com.za.call.CallLogManager
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import java.util.concurrent.atomic.AtomicBoolean

open class BaseActivityLifecycleCallbacks : ActivityLifecycleCallbacks {


	override fun onActivityCreated(activity : Activity, savedInstanceState : Bundle?) {
		LogUtil.print("onActivityCreated", activity.javaClass.simpleName)
		keepScreenOn(activity)
	}


	override fun onActivityStarted(activity : Activity) {
		LogUtil.print("onActivityStarted", activity.javaClass.simpleName)
		synchronized(this) {
			GlobalData.activityCount ++
			if (GlobalData.activityCount == 1) {
				isBackground.set(false)
				appForegroundListener?.onAppForeground()
				LogUtil.print("AppState", "切换到前台")
			}
		}
	}

	override fun onActivityResumed(activity : Activity) {
		LogUtil.print("onActivityResumed", activity.javaClass.simpleName)
		currentActivity = activity
		CallLogManager.uploadCallLog(activity.applicationContext)
	}

	override fun onActivityPaused(activity : Activity) {
		LogUtil.print("onActivityPaused", activity.javaClass.simpleName)
		if (currentActivity == activity) {
			currentActivity = null
		}
	}

	override fun onActivityStopped(activity : Activity) {
		LogUtil.print("onActivityStopped", activity.javaClass.simpleName)
		synchronized(this) {
			GlobalData.activityCount --
			if (GlobalData.activityCount == 0) {
				isBackground.set(true)
				appForegroundListener?.onAppBackground()
				LogUtil.print("AppState", "切换到后台")
			}
		}
	}


	override fun onActivitySaveInstanceState(activity : Activity, outState : Bundle) {
		LogUtil.print("onActivitySaveInstanceState", activity.javaClass.simpleName)
	}

	override fun onActivityDestroyed(activity : Activity) {
		LogUtil.print("onActivityDestroyed", activity.javaClass.simpleName)
	}

	private fun keepScreenOn(activity : Activity) { //保持屏幕不息屏
		activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
	}

	companion object {
		var appForegroundListener : AppForegroundListener? = null

		// 使用 AtomicBoolean 保证线程安全
		private val isBackground = AtomicBoolean(true)

		// 当前显示的Activity
		private var currentActivity : Activity? = null

		// 判断应用是否在后台
		fun isBackground() : Boolean = isBackground.get()

		// 判断应用是否在前台
		fun isForeground() : Boolean = ! isBackground.get()

		// 获取当前Activity
		fun getCurrentActivity() : Activity? = currentActivity

		// 重置状态
		fun reset() {
			synchronized(BaseActivityLifecycleCallbacks::class.java) {
				isBackground.set(true)
				currentActivity = null
				appForegroundListener = null
			}
		}
	}
}