package com.ujuad.demo.helper

import android.app.Activity
import android.view.ViewGroup
import com.ujuad.demo.constant.DemoConfig
import com.ujuad.demo.listener.PrintLogger
import com.ujuad.demo.utils.DemoLogUtils
import com.ujusdk.adsdk.exception.UjuException
import com.ujusdk.adsdk.public.config.UjuAdConfig
import com.ujusdk.adsdk.public.listener.SplashAdObjectListener
import com.ujusdk.adsdk.public.objects.SplashAdObject

/**
 * @CreateDate: 2026/2/4 16:24
 * @Author: 青柠
 * @Description:
 */
class SplashAdHelper(private val activity: Activity, private val logger: PrintLogger) {

    private var splashAdObject: SplashAdObject? = null

    fun load() {
        val adConfig = UjuAdConfig(
            placementId = DemoConfig.SPLASH_ID,
        )
        splashAdObject = SplashAdObject(activity, adConfig)
        splashAdObject?.setAdObjectListener(object : SplashAdObjectListener {
            override fun onLoadSuccess(placementId: String) {
                //广告加载成功,此时可以展示，建议展示前判断isReady
                logger.add("Splash: onLoadSuccess")
            }

            override fun onAdShow() {
                val adInfo = splashAdObject?.getAdInfo()
                logger.add("Splash: onAdShow,ecpm:${adInfo?.ecpm}")
            }

            override fun onAdError(
                error: UjuException,
                placementId: String
            ) {
                logger.add("Splash: onAdError：${error.message}")
                DemoLogUtils.e("onAdError：${error.message}")
            }

            override fun onAdClicked() {
                logger.add("Splash: onAdClicked")
            }

            override fun onAdClosed() {
                logger.add("Splash: onAdClosed")

                splashAdObject?.destroy()
                splashAdObject = null
            }

            override fun onLoadError(
                error: UjuException,
                placementId: String
            ) {
                logger.add("Splash: onLoadError: ${error.message}")
                DemoLogUtils.e("onLoadError：${error.message}")
            }
        })

        splashAdObject?.load()
        logger.add("Splash: load, placementId:${adConfig.placementId}")
        DemoLogUtils.d("Splash: load, placementId:${adConfig.placementId}")
    }

    fun show(viewGroup: ViewGroup) {
        if (splashAdObject?.isReady() == true) {
            splashAdObject?.show(activity, viewGroup)
        } else {
            logger.add("Splash: 广告还未准备好")
        }
    }

    fun isLoaded(): Boolean {
        return splashAdObject != null
    }

    fun destroy() {
        splashAdObject?.destroy()
        splashAdObject = null
    }
}