package com.apps.quicksketchtrace.activity

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.apps.quicksketchtrace.ad.MetaFacebookLDUHelper
import com.apps.quicksketchtrace.ad.TPManager
import com.apps.quicksketchtrace.databinding.ActivityMainStartBinding


import com.google.android.ump.ConsentForm
import com.google.android.ump.ConsentInformation
import com.google.android.ump.ConsentRequestParameters
import com.google.android.ump.UserMessagingPlatform
import com.tradplus.ads.base.common.TPPrivacyManager.OnPrivacyRegionListener
import com.tradplus.ads.open.TradPlusSdk
import com.tradplus.ads.open.TradPlusSdk.TradPlusInitListener
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class StartMainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainStartBinding
    private var countDownTimer: CountDownTimer? = null
    private var isRunning = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainStartBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setPrivacyConsent()
    }

    private fun intentMain() {
        startActivity(Intent(this@StartMainActivity, MainActivity::class.java))
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()

    }

    private fun setPrivacyConsent() {
        // Google UMP
        val params: ConsentRequestParameters? =
            ConsentRequestParameters.Builder() // 指示用户是否低于同意年龄; true 低于同意年龄
                // 未满同意年龄的用户不会收到 GDPR 消息表单
                .setTagForUnderAgeOfConsent(false)
                .build()

        val consentInformation: ConsentInformation =
            UserMessagingPlatform.getConsentInformation(this)
        consentInformation.requestConsentInfoUpdate(
            this,
            params,
            ConsentInformation.OnConsentInfoUpdateSuccessListener {
                UserMessagingPlatform.loadAndShowConsentFormIfRequired(
                    this,
                    ConsentForm.OnConsentFormDismissedListener { loadAndShowError ->
                        if (loadAndShowError != null) {
                            // Consent gathering failed.
                        }
                        // Consent has been gathered.
                        if (consentInformation.canRequestAds()) {
                            Log.i("TP AD", "授权完成,初始化SDK: ")
                            // 授权完成,初始化SDK
                            initTPSDK()
                        }
                    } as ConsentForm.OnConsentFormDismissedListener)
            } as ConsentInformation.OnConsentInfoUpdateSuccessListener,
            ConsentInformation.OnConsentInfoUpdateFailureListener { requestConsentError -> } as ConsentInformation.OnConsentInfoUpdateFailureListener)


        // 用户已经进行过UMP选择
        if (consentInformation.canRequestAds()) {
            // 授权完成,初始化SDK
            Log.i("TP AD", "用户已经进行过UMP选择,初始化SDK: ")
            initTPSDK()
        }

        // 集成Google UMP后; 如果美国加州没有投放APP，无需调用
        checkAreaSetCCPA();
    }


    private fun checkAreaSetCCPA() {
        // 判断用户是否已经选择过，返回true表示已经进行过选择，就不需要再次进行GDPR弹窗
        val firstShowGDPR = TradPlusSdk.isFirstShowGDPR(this)
        // 查询地区
        TradPlusSdk.checkCurrentArea(this, object : OnPrivacyRegionListener {
            override fun onSuccess(isEu: Boolean, isCn: Boolean, isCalifornia: Boolean) {
                // 获取到相关地域配置后，设置相关隐私API

                // 集成Google UMP后无需处理欧洲地区
                // 表明是欧洲地区，设置GDPR弹窗
//                if (isEu) {
//                    if (!firstShowGDPR) {
//                        TradPlusSdk.showUploadDataNotifyDialog(application, new TradPlusSdk.TPGDPRAuthListener() {
//                            @Override
//                            public void onAuthResult(int level) {
//                                // 获取设置结果并做记录，true 表明用户 进行过选择
//                                TradPlusSdk.setIsFirstShowGDPR(application, true);
//                            }
//                        }, Const.URL.GDPR_URL); // Const.URL.GDPR_URL 为TradPlus 定义的授权页面
//                    }
//                }

                // 表明是美国加州地区，设置CCPA
                Log.i("TP AD", "onSuccess isCalifornia=${isCalifornia} ")
                if (isCalifornia) {
                    // false 加州用户均不上报数据 ；true 接受上报数据
                    // 默认不上报，如果上报数据，需要让用户选择
                    TradPlusSdk.setCCPADoNotSell(this@StartMainActivity, false)
                    MetaFacebookLDUHelper.enableLDUForCalifornia()
                }

                if (!isEu) {
                    Log.i("TP AD", "isEu= initTPSDK ")
                    initTPSDK()
                }
            }

            override fun onFailed() {
                // 一般为网络问题导致查询失败，开发者需要自己判断地区，然后进行隐私设置
                // 然后在初始化SDK
                Log.i("TP AD", "onFailed ")
                MetaFacebookLDUHelper.checkAndEnableLDU(this@StartMainActivity)
                initTPSDK()
            }
        })
    }


    @OptIn(DelicateCoroutinesApi::class)
    private fun initTPSDK() {
        GlobalScope.launch(Dispatchers.Main) {
            if (!TradPlusSdk.getIsInit()) {
                TradPlusSdk.setTradPlusInitListener(object : TradPlusInitListener {
                    override fun onInitSuccess() {
                        Log.i("TP AD", "onInitSuccess: ")
                        startCountDown()
                        TPManager.loadAllAd(this@StartMainActivity)
                    }
                })
                TradPlusSdk.initSdk(this@StartMainActivity, "4A8326375DB61EDF3B8AD4CD231177E8")

            }
        }

    }

    private fun startCountDown() {
        val total = 12000L
        countDownTimer = countDownTimer ?: TPManager.showWelcomeAd(
            this@StartMainActivity,
            total,
            { millisUntilFinished ->
                isRunning = true
                var progressPercentage = ((100 * millisUntilFinished) / total)
                val i = (100 - progressPercentage).toInt()
                Log.i("TP AD", "=${i} ")
                binding.progressbar.progress = i
            }) {
            binding.progressbar.progress = 100
            intentMain()
        }
        if (!isRunning) {
            countDownTimer?.start()
        }

    }
}