package com.convenient.android.lib

import android.app.Application
import android.content.Intent
import androidx.lifecycle.*
import com.composition.android.lib.ad.AdLoad
import com.convenient.android.common.extension.readyGo
import com.convenient.android.lib.ui.sample.ad.activity.AppWelcomeActivity
import com.convenient.android.lib.ui.sample.ad.model.Datas
import kotlinx.coroutines.launch

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/6
 * description:
 */
class LibApplication : Application(), LifecycleEventObserver {

    override fun onCreate() {
        super<Application>.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when(event){
            Lifecycle.Event.ON_START->{
                ProcessLifecycleOwner.get().lifecycleScope.launch {
                    if (AdLoad.hasCacheAd(Datas.APP_OPEN) && Datas.bgShowAppOpen) {
                        readyGo(AppWelcomeActivity::class.java){
                            it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            it.putExtra(AppWelcomeActivity.ONLY_SHOW, true)
                        }
                    }
                }
            }
            Lifecycle.Event.ON_PAUSE->{
                if (Datas.bgShowAppOpen){
                    ProcessLifecycleOwner.get().lifecycleScope.launch {
                        AdLoad.preloadAd(this@LibApplication, Datas.APP_OPEN)
                    }
                }
            }
            else->{

            }

        }
    }

}