package com.convenient.android.lib.ui.sample.ad.activity

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.composition.android.lib.ad.AdLoad
import com.composition.android.lib.ad.basic.AdResult
import com.convenient.android.common.base.viewbinding.BaseBindingActivity
import com.convenient.android.common.extension.readyGo
import com.convenient.android.lib.MainActivity
import com.convenient.android.lib.databinding.ActivityAppWelcomeBinding
import com.convenient.android.lib.ui.sample.ad.model.Datas
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/9
 * description:
 */
class AppWelcomeActivity : BaseBindingActivity<ActivityAppWelcomeBinding>(ActivityAppWelcomeBinding::inflate) {

    companion object {
        const val ONLY_SHOW = "only_show"
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {

            val onlyShow = intent.getBooleanExtra(ONLY_SHOW, false)
            if (onlyShow) {
                showAd {
                    lifecycleScope.launch {
                        delay(300)
                        finish()
                    }
                }
            }else{
                showAd {
                    toGoMainActivity()
                }
            }
        }
    }

    private suspend fun showAd(result : () -> Unit){

        AdLoad.loadAd(this, Datas.APP_OPEN)
            .collect{
                if (it is AdResult.Success){
                    delay(200)
                    AdLoad.showSplash(this, binding.llAdContent, it){
                        onAdClose {
                            result.invoke()
                        }
                        onAdLoadedFail {
                            result.invoke()
                        }
                        onAdSkip {
                            result.invoke()
                        }
                        onTimeOver {
                            result.invoke()
                        }
                    }
                }else{
                    result.invoke()
                }
            }
    }


    private fun toGoMainActivity(delay : Long = 3000){

        lifecycleScope.launch {
            delay(delay)
            this@AppWelcomeActivity.readyGo(MainActivity::class.java)
            finish()
        }

    }
}

