package com.shenghuoquan.business

import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import com.orhanobut.hawk.Hawk
import com.yidian.bcommon.app.YdBaseApplication
import com.yidian.bcommon.constant.GlobalConstants
import com.yidian.bcommon.services.AppUpgradeService
import com.yidian.bcommon.services.ImageService
import com.yidian.bcommon.services.XEventService
import com.yidian.bcommon.services.XPageService
import com.yidian.commonutil.CommonUtilLifecycleModule
import com.yidian.news.util.ProcessUtil
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.core.YacAppSpec
import com.yidian.yac.core.zap.Zap
import timber.log.Timber


@YacAppSpec
class BusinessApplication : YdBaseApplication() {

  override fun onCreate() {
    super.onCreate()
    if (ProcessUtil.isMainProcess(this)) {
      context = this
      // 先初始化日志防止调用时报初始化异常
      if (BuildConfig.DEBUG) {
        Timber.plant(Timber.DebugTree())
      }
      initCommonUtils()
      Zap.init(this) {}
      XPageManager.init(this)
      loadService()
      registerActivityLifecycleCallbacks(activityLifecycle)
      initEnvironment()
    }
  }

  private fun initEnvironment() {
    GlobalConstants.ENVIRONMENT = BuildConfig.FLAVOR
    GlobalConstants.AUTHORITY = BuildConfig.PROVIDER_NAME
  }

  override fun attachBaseContext(base: Context?) {
    super.attachBaseContext(base)
    if (ProcessUtil.isMainProcess(this)) {
      module.onBaseContextAttached(base)
    }
  }

  override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    if (ProcessUtil.isMainProcess(this)) {
      module.onConfigurationChanged(newConfig)
    }
  }

  private fun initCommonUtils() {
    module.onCreate()
    Hawk.init(this).build()
  }

  private val module: CommonUtilLifecycleModule by lazy {
    CommonUtilLifecycleModule(
      com.yidian.xarc.xbrid.BuildConfig.DEBUG,
      this,
      ".CommonInfrastructure"
    )
  }

  private val activityLifecycle = object : ActivityLifecycleCallbacks {

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
      activityList.add(activity)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

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

    }

    override fun onActivityDestroyed(activity: Activity) {
      activityList.remove(activity)
    }

  }

  private fun loadService() {
    Zap.addService(XPageService.SERVICE_NAME, XPageService())
    Zap.addService(XEventService.SERVICE_NAME, XEventService())
    Zap.addService(AppUpgradeService.SERVICE_NAME, AppUpgradeService())
    Zap.addService(ImageService.SERVICE_NAME, ImageService())
  }

}
