package com.assimilate.alltrans

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.webkit.WebView
import com.assimilate.alltrans.common.AppStore
import com.assimilate.alltrans.common.RemoteConfigManager
import com.assimilate.alltrans.model.LanguagesConstants
import com.assimilate.alltrans.model.PreferenceLanguageUtils
import com.assimilate.alltrans.viewui.WelActivity
import com.lol.apex.ok.google.adlibrary.LoLAds
import com.lol.apex.ok.google.adlibrary.bean.constants.TestMode
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong

class MyApp : Application() {
    init {
        instance = this
    }

    private var activityReferences = 0
    private var isActivityChangingConfigurations = false

    var isFirstLaunch = true
    var isFirstPremisiton = false

    private fun registerActivityLifecycle() {

        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            }

            override fun onActivityStarted(activity: Activity) {

                if (++activityReferences == 1 && !isActivityChangingConfigurations) {
                    // Log.d("MyApplication", "应用进入前台")
                    if (!isFirstLaunch) {
                        if (isFirstPremisiton) return
                        val intent = Intent(activity, WelActivity::class.java)
                        activity.startActivity(intent)
                    }
                }
            }

            override fun onActivityResumed(activity: Activity) {}

            override fun onActivityPaused(activity: Activity) {}

            override fun onActivityStopped(activity: Activity) {

                isActivityChangingConfigurations = activity.isChangingConfigurations
                if (--activityReferences == 0 && !isActivityChangingConfigurations) {

                    isFirstLaunch = false
                    // Log.d("MyApplication", "应用进入后台")
                }
            }

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

            override fun onActivityDestroyed(activity: Activity) {

            }
        })
    }

    private fun setSystemLanguage() {
        // 检查是否是第一次进入应用
        if (PreferenceLanguageUtils.isFirstTime()) {
            // 第一次进入应用的逻辑
            val config = applicationContext().resources.configuration
            val locale = config.locale.toString()  // 获取完整的语言环境信息，如 "en_US" 或 "zh_CN"
            val languages = LanguagesConstants.getInstance().getLanguageByLanguageCode(locale, this)

            PreferenceLanguageUtils.putString(
                "language_target",
                languages.language.toString().trim()
            )
            // 设置已经不是第一次进入应用了
            PreferenceLanguageUtils.setNotFirstTime()
        }
    }

    // 用于记录上次广告展示的时间
    val lastAdDisplayTime: AtomicLong = AtomicLong(0)
    val isAdShowing: AtomicBoolean = AtomicBoolean(false)

    companion object {
        private var instance: MyApp? = null

        fun applicationContext(): Context {
            return instance!!.applicationContext
        }

        val app: MyApp
            get() = instance!!
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        registerActivityLifecycle()
        initAd()
        setSystemLanguage()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getUniqueProcessName()
            if (processName != null && processName != packageName) {
                WebView.setDataDirectorySuffix(processName)
            }
        }
    }

    private fun getUniqueProcessName(): String? {
        val pid = android.os.Process.myPid()
        val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (processInfo in manager.runningAppProcesses) {
            if (processInfo.pid == pid) {
                return processInfo.processName
            }
        }
        return null
    }


    private fun initAd() {
        //初始化firebase，并获取firebase值
        RemoteConfigManager(this)

        LoLAds.initialize(this)
        LoLAds.setLogEnable(BuildConfig.DEBUG)//是否打开⽇志和遮罩层颜色，release要设置成false
        LoLAds.setTestEnable(BuildConfig.DEBUG)//false：使用 setAdConfig 中的广告配置
        LoLAds.setTestMode(TestMode.REMOTE_TEST)//setTestEnable为true时生效；LOCAL_TEST: 会使用sdk内的测试广告; REMOTE_TEST: 会将 setAdConfig 添加的配置中的广告id替换成测试id
        //服务器端中⼴告json的key；⻅⼴告配置json详情
        LoLAds.setAdConfigKey(Config.adKey)
        //设置自定义广告配置json
        val config = AppStore(app).adMessage.takeIf { it.isNotEmpty() } ?: Config.adDefJson
        LoLAds.setAdConfig(config)
    }

    object Config {

        // firebase_event_map_key
        const val CLICK_FROM = "clickfrom"
        const val FAIL_REASON = "failreason"
        const val LAN_SOURCE = "source"
        const val LAN_TARGET = "target"

        // firebase_event_key
        const val launchPv = "launch_pv"
        const val homePv = "home_pv"
        const val languageChoose = "language_choose"
        const val languageFrom = "language_from"
        const val textTransSwitch = "text_trans_switch"
        const val textInput = "text_input"
        const val textTransClick = "text_trans_click"
        const val textTransResult = "text_trans_result"
        const val textTransPaste = "text_trans_paste"

        const val textVoiceClick = "text_voice_click"
        const val textVoiceResult = "text_voice_result"
        const val textTransPlay = "text_trans_play"
        const val textTransCopy = "text_trans_copy"
        const val textTransShare = "text_trans_share"
        const val textTransLike = "text_trans_like"

        const val hoverButtonClick = "hover_button_click"
        const val hoverLimitAgree = "hover_limit_agree"
        const val hoverButtonCancel = "hover_button_cancel"
        const val hoverButtonAgree = "hover_button_agree"
        const val hoverScreenClick = "hover_screen_click"
        const val hoverScreenImp = "hover_screen_imp"
        const val hoverScreenGlobal = "hover_screen_global"
        const val hoverGlobalResult = "hover_global_result"
        const val hoverScreenDistrict = "hover_screen_district"
        const val hoverDistrictResult = "hover_district_result"

        const val imageClick = "image_click"
        const val imageTransCamera = "image_trans_camera"
        const val imageCameraResult = "image_camera_result"
        const val imageTransPhoto = "image_trans_photo"
        const val imagePhotoResult = "image_photo_result"

        const val historyClick = "history_click"
        const val historyDelete = "history_delete"

        const val directoryClick = "directory_click"
        const val directoryTransClick = "directory_trans_click"
        const val directoryTransResult = "directory_trans_result"


        // google_ad_place
        const val start_cold_int_auto = "start_cold_int_auto"
        const val start_hot_int_auto = "start_hot_int_auto"
        const val text_trans_int_auto = "text_trans_int_auto"
        const val text_new_int_auto = "text_new_int_auto"
        const val text_camera_int_auto = "text_camera_int_auto"
        const val image_camera_int_auto = "image_camera_int_auto"
        const val history_int_auto = "history_int_auto"
        const val directory_int_auto = "directory_int_auto"
        const val home_native_auto = "home_native_auto"
        const val text_trans_native_auto = "text_trans_native_auto"
        const val backup_int_auto = "backup_int_auto"


        const val adKey = "alltrans"
        const val adDefJson = """
            {
  "AD_SHOW_LIMIT": {
    "admob_inst": 100,
    "admob_native": 100,
    "max_banner": 100,
    "max_inst": 100,
    "max_native": 100
  },
  "sounds_inst_show_interval": 25000,
  "LOLAds_EXPIRE_HOURS_NEW_USER": 20,
  "alltrans_start_cold_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/2491776559": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_start_hot_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/8726012415": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_text_trans_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/8833823620": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_text_new_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/7552531544": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_text_camera_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/3473685732": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_image_camera_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/9094248890": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_history_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/9160460404": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_directory_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/1975489976": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  },
  "alltrans_home_native_auto": {
    "data": [
      {
        "config": [
          [
            "admob_native",
            {
              "ca-app-pub-9280511366580942/6663526672": 100
            }
          ]
        ],
        "block": {
          "admob_native": {
            "delay": 0,
            "rate": 0
          },
          "max_native": {
            "delay": 0,
            "rate": 0
          }
        },
        "click": {
          "admob_native": [
            100,
            100,
            100,
            100,
            100
          ],
          "max_native": [
            100,
            100,
            100,
            100,
            100
          ]
        },
        "after_click": {
          "admob_native": "next",
          "max_native": "next"
        },
        "limit": {
          "admob_native": 100,
          "max_native": 100
        }
      }
    ]
  },
  "alltrans_text_trans_native_auto": {
    "data": [
      {
        "config": [
          [
            "admob_native",
            {
              "ca-app-pub-9280511366580942/6930403378": 100
            }
          ]
        ],
        "block": {
          "admob_native": {
            "delay": 0,
            "rate": 0
          },
          "max_native": {
            "delay": 0,
            "rate": 0
          }
        },
        "click": {
          "admob_native": [
            100,
            100,
            100,
            100,
            100
          ],
          "max_native": [
            100,
            100,
            100,
            100,
            100
          ]
        },
        "after_click": {
          "admob_native": "next",
          "max_native": "next"
        },
        "limit": {
          "admob_native": 100,
          "max_native": 100
        }
      }
    ]
  },
  "alltrans_backup_int_auto": {
    "data": [
      {
        "after_click": {
          "admob_inst": "keep",
          "max_inst": "keep"
        },
        "block": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "close": {
          "admob_inst": {
            "delay": 0,
            "rate": 0
          },
          "max_inst": {
            "delay": 0,
            "rate": 0
          }
        },
        "config": [
          [
            "admob_inst",
            {
              "ca-app-pub-9280511366580942/8739025670": 100
            }
          ]
        ],
        "limit": {
          "admob_inst": 100,
          "max_inst": 100
        },
        "cycle": 0,
        "timeout": 15000,
        "showIntervalEnable": false
      }
    ]
  }
}
        """
    }
}
